Why doesn't Java accept my LinkedList in Generic, but accepts it?
We cannot use any types of bultin languages for class assignment, so I am stuck with my own list. Anyway, here's the situation:
public class CrazyStructure <T extends Comparable<? super T>> {
MyLinkedList<MyTree<T>> trees; //error: type parameter MyTree is not within its bound
}
But:
public class CrazyStructure <T extends Comparable<? super T>> {
LinkedList<MyTree<T>> trees;
}
Working. MyTree implements the Comparable interface, but MyLinkedList does not. However Java's LinkedList does not implement it, according to this . So what is the problem and how to fix it?
MyLinkedList:
public class MyLinkedList<T extends Comparable<? super T>> {
private class Node<T> {
private Node<T> next;
private T data;
protected Node();
protected Node(final T value);
}
Node<T> firstNode;
public MyLinkedList();
public MyLinkedList(T value);
//calls node1.value.compareTo(node2.value)
private int compareElements(final Node<T> node1, final Node<T> node2);
public void insert(T value);
public void remove(T value);
}
MyTree:
public class LeftistTree<T extends Comparable<? super T>>
implements Comparable {
private class Node<T> {
private Node<T> left, right;
private T data;
private int dist;
protected Node();
protected Node(final T value);
}
private Node<T> root;
public LeftistTree();
public LeftistTree(final T value);
public Node getRoot();
//calls node1.value.compareTo(node2.value)
private int compareElements(final Node node1, final Node node2);
private Node<T> merge(Node node1, Node node2);
public void insert(final T value);
public T extractMin();
public int compareTo(final Object param);
}
a source to share
I am assuming your MyTree is the same as LeftistTree. The problem with signature is that it doesn't implement Comparable<LeftistTree<? super T>>
.
So, the signature should be:
public class LeftistTree<T extends Comparable<? super T>>
implements Comparable<LeftistTree<? super T>>
The reason is that your MyLinkedList is not like a regular LinkedList. A normal LinkedList has a type: LinkedList<T>
no constraint on T. You require MyLinkedList for this parameter to implement Comparable itself (or its superclass), but in fact LeftistTree implements raw Comparable (or Comparable<?>
), so the compiler is not guaranteed to be associated with the type.
a source to share
Why should your linked list take over Comparable
?
For a collection data structure, enforcing your collection only for a specific data type is very limited. If you want to have a sorted linked list, it is better to accept any item and allow the linked list to accept an object Comparator
. If you don't Comparator
, then you can rely on the natural order of the contained element, if they have Comparable
.
Take a look at SortedSet or SortedMap api signature for some example.
a source to share