Java泛型绑定不匹配错误
我正在用Java编写一个通用链表实现。代码是Java泛型绑定不匹配错误,java,generics,Java,Generics,我正在用Java编写一个通用链表实现。代码是 public class LinkedList<T> { private Node<T> top; private int no_of_items; private class Node<T extends Comparable<? super T>> { T data; Node<T> next; } public
public class LinkedList<T> {
private Node<T> top;
private int no_of_items;
private class Node<T extends Comparable<? super T>> {
T data;
Node<T> next;
}
public LinkedList() {
top = null;
}
public boolean isEmpty() {
return (top == null);
}
public void insert(T item) {
Node<T> node = new Node<T>();
node.data = item;
node.next = top;
if(isEmpty()) {
top = node;
} else {
Node<T> n = top;
while(n.next != null) {
n = n.next;
}
n.next = node;
}
no_of_items++;
}
}
我无法找出这里的问题所在。我自己解决了错误。正确的代码应该是
public class LinkedList<T extends Comparable<? super T>> {
private Node top;
private int no_of_items;
private class Node {
T data;
Node next;
}
public LinkedList() {
top = null;
}
public boolean isEmpty() {
return (top == null);
}
public void insert(T item) {
Node node = new Node();
node.data = item;
node.next = top;
if(isEmpty()) {
top = node;
} else {
Node n = top;
while(n.next != null) {
n = n.next;
}
n.next = node;
}
no_of_items++;
}
}
public class LinkedList不编辑带有答案的问题,而是将其作为答案发布并接受。由于我是新成员,我在10小时内不允许发布自己问题的答案,因此我对其进行了编辑。如果你已经解决了你的问题,那么你可以将它标记为“已接受”。没有任何理由在标题中添加“已解决”,因为公认的答案可以被视为等效答案。感谢Makoto删除“已解决”。最初是我编辑答案的时候
public class LinkedList<T extends Comparable<? super T>> {
private Node top;
private int no_of_items;
private class Node {
T data;
Node next;
}
public LinkedList() {
top = null;
}
public boolean isEmpty() {
return (top == null);
}
public void insert(T item) {
Node node = new Node();
node.data = item;
node.next = top;
if(isEmpty()) {
top = node;
} else {
Node n = top;
while(n.next != null) {
n = n.next;
}
n.next = node;
}
no_of_items++;
}
}