为什么Java不接受Generic中的LinkedList,但接受它自己的?

mas*_*ief 2 java linked-list comparable

对于课堂作业,我们不能使用任何bultin类型的语言,所以我坚持使用自己的列表.无论如何,这是情况:

public class CrazyStructure <T extends Comparable<? super T>> {
    MyLinkedList<MyTree<T>> trees; //error: type parameter MyTree is not within its bound
}
Run Code Online (Sandbox Code Playgroud)

然而:

public class CrazyStructure <T extends Comparable<? super T>> {
    LinkedList<MyTree<T>> trees;
}
Run Code Online (Sandbox Code Playgroud)

作品.MyTree实现Comparable接口,但MyLinkedList没有.但是,根据这一点,Java的LinkedList也没有实现它.那么问题是什么,我该如何解决?

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);
}
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

Yis*_*hai 5

我假设您的MyTree与LeftistTree相同.签名的问题在于它没有实现Comparable<LeftistTree<? super T>>.

签名应该是:

public class LeftistTree<T extends Comparable<? super T>>
    implements Comparable<LeftistTree<? super T>>
Run Code Online (Sandbox Code Playgroud)

原因是您的MyLinkedList不像常规的LinkedList.常规LinkedList的类型是:LinkedList<T>T上没有边界.您需要MyLinkedList,该参数实现自身(或其超类)的Comparable,但实际上LeftistTree正在实现原始Comparable(或Comparable<?>),因此Comparable不能保证与类型有关.