我尝试制作一个通用链表。
此链表的节点使用 <T extends Comparable <T>>
。但是当我使用
LList<LList<Integer>> linkedlist = new LList<LList<Integer>>();
创建新实例时出现错误:
Multiple markers at this line
- Bound mismatch: The type LList<Integer> is not a valid substitute
for the bounded parameter <T extends Comparable<T>> of the type LList<T>
- Bound mismatch: The type LList<Integer> is not a valid substitute
for the bounded parameter <T extends Comparable<T>> of the type
如何解决这个问题?
<小时/> 节点类:public class Node <T extends Comparable <T>> {
// Members:
public T data;
public Node <T> next;
// Methods:
public Node () {
data =null;
next = null;
}
public Node (T data) {
this.data = data;
next = null;
}
}
LList类:
public class LList <T extends Comparable <T>> {
// Members:
public Node <T> head;
// Methods:
public LList () {
head = null;
}
// Add node.
public void addNode (T data) {
if (head == null) {
head = new Node <T> (data);
return;
}
Node <T> newNode = new Node <T> (data);
Node <T> tempNode = head;
while (tempNode.next != null) tempNode = tempNode.next;
tempNode.next = newNode;
}
// Show linked list.
public void showLLForInteger () {
if (head == null) return;
Node <T> tempNode = head;
while (tempNode != null) {
System.out.print(String.format("%-6d", tempNode.data));
tempNode = tempNode.next;
}
System.out.println();
}
}
最佳答案
您为什么需要
T extends Comparable<T>
?您似乎没有在任何地方使用它。既然您需要
T extends Comparable<T>
,这意味着列表的参数必须与其自身进行比较。LList<LList<Integer>>
不起作用,因为LList<Integer>
与自身不可比较(它不扩展Comparable<LList<Integer>>
)。你确定你不只是想要LList<Integer>
?
关于java - 如何实现扩展 Comparable 的列表列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22901375/