gpt4 book ai didi

Java 泛型绑定(bind)不匹配错误

转载 作者:行者123 更新时间:2023-12-01 14:53:36 25 4
gpt4 key购买 nike

我正在用 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 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++;

}
}

我想要的是T应该是Comparable。编译此代码时,我在初始化节点时收到错误。

Bound Mismatch the type T is not a valid substitute for the bounded parameter <T extends Comparable<? super T>> of the type LinkedList<T>.Node<T>

我无法弄清楚这里出了什么问题。

最佳答案

我自己解决了这个错误。正确的代码是

    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++;

}
}

答案在于,当我们在顶级类中使用泛型类型 T 并且我们有非静态内部类时,相同的 T 在内部类中也是可见的。

谢谢

关于Java 泛型绑定(bind)不匹配错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14545437/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com