M
Mark Maloof
I need an ordered sequence, so I extended LinkedList<T>. Since I'm
implementing an ordered collection, its elements must implement
Comparable<T>. I came up with the following implementation, which
seems to work, but I cannot figure out how to avoid the unchecked cast
at the end of the insert method:
public class OrderedLinkedList<E> extends LinkedList<E> {
public void insert( Comparable<E> element ) {
int i = 0;
while ( i < size() && element.compareTo( this.get( i ) ) >= 0 ) {
i++;
} // while
// add( i, element ); // compiler error
add( i, (E) element ); // unchecked cast
} // OrderedLinkedList::add
public static void main ( String args[] ) {
OrderedLinkedList<String> oll = new OrderedLinkedList<String>();
oll.insert("cat");
oll.insert("pig");
oll.insert("dog");
oll.insert("hog");
System.out.println( oll );
} // OrderedLinkedList::main
} // OrderedLinkedList class
I'm familiar with Bracha's tutorial and Langer's FAQ, and I've spent a
fair amount of time pounding Google, but I haven't found anything that
deals with this particular issue. (Pointers would be appreciated.) My
intuition tells me that I need to indicate somehow that E extends
Comparable (since LinkedList.add takes an E), but I haven't figured out
how to write something that compiles. Any help would be appreciated.
Mark
implementing an ordered collection, its elements must implement
Comparable<T>. I came up with the following implementation, which
seems to work, but I cannot figure out how to avoid the unchecked cast
at the end of the insert method:
public class OrderedLinkedList<E> extends LinkedList<E> {
public void insert( Comparable<E> element ) {
int i = 0;
while ( i < size() && element.compareTo( this.get( i ) ) >= 0 ) {
i++;
} // while
// add( i, element ); // compiler error
add( i, (E) element ); // unchecked cast
} // OrderedLinkedList::add
public static void main ( String args[] ) {
OrderedLinkedList<String> oll = new OrderedLinkedList<String>();
oll.insert("cat");
oll.insert("pig");
oll.insert("dog");
oll.insert("hog");
System.out.println( oll );
} // OrderedLinkedList::main
} // OrderedLinkedList class
I'm familiar with Bracha's tutorial and Langer's FAQ, and I've spent a
fair amount of time pounding Google, but I haven't found anything that
deals with this particular issue. (Pointers would be appreciated.) My
intuition tells me that I need to indicate somehow that E extends
Comparable (since LinkedList.add takes an E), but I haven't figured out
how to write something that compiles. Any help would be appreciated.
Mark