[英]How to implement my own LinkedList<LinkedList> data structure in Java?
[英]How come Java doesn't accept my LinkedList in a Generic, but accepts its own?
对于班级分配,我们不能使用bultin类型的任何语言,因此我只能使用自己的列表。 无论如何,这是情况:
public class CrazyStructure <T extends Comparable<? super T>> {
MyLinkedList<MyTree<T>> trees; //error: type parameter MyTree is not within its bound
}
然而:
public class CrazyStructure <T extends Comparable<? super T>> {
LinkedList<MyTree<T>> trees;
}
作品。 MyTree实现Comparable接口,但MyLinkedList没有。 但是,根据this ,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);
}
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);
}
我假设您的MyTree与LeftistTree相同。 签名的问题在于它没有实现Comparable<LeftistTree<? super T>>
Comparable<LeftistTree<? super T>>
。
因此签名应为:
public class LeftistTree<T extends Comparable<? super T>>
implements Comparable<LeftistTree<? super T>>
原因是您的MyLinkedList与常规的LinkedList不同。 常规LinkedList的类型为: LinkedList<T>
在LinkedList<T>
上没有界限。您需要使用MyLinkedList来使参数实现自身(或它的超类)的Comparable,但实际上LeftistTree在实现原始的Comparable(或Comparable<?>
),因此不保证Comparable与类型相关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.