我是泛型的新手,我正在尝试使用泛型类 SinglyLinkedNode 实现链表。但是,当我运行 setData() 和 setNext() 方法时,出现以下错误:
.\singlyLinkedList\SinglyLinkedNode.java:13: error: incompatible types: T#1 cannot be
converted to T#2
this.data = d;
^
where T#1,T#2 are type-variables:
T#1 extends Object declared in method <T#1>setData(T#1)
T#2 extends Object declared in class SinglyLinkedNode
.\singlyLinkedList\SinglyLinkedNode.java:21: error: incompatible types:
SinglyLinkedNode<T#1> cannot be converted to SinglyLinkedNode<T#2>
this.next = n;
^
where T#1,T#2 are type-variables:
T#1 extends Object declared in method <T#1>setNext(SinglyLinkedNode<T#1>)
T#2 extends Object declared in class SinglyLinkedNode
在我看来,抛出错误是因为存在一种潜在的场景,其中预先存在的 this.data 或 this.next 的类型与 d 或 n 不匹配。我怎样才能解决这个问题?有什么方法可以用 T#2(新数据)覆盖 T#1(预先存在的数据)的类型?这是带有我的构造函数和 setter 方法的类:
public class SinglyLinkedNode<T> {
private T data;
private SinglyLinkedNode<T> next;
SinglyLinkedNode(T d) {
this.data = d;
this.next = null;
}
public <T> void setData(T d) {
this.data = d;
}
//...
public <T> void setNext(SinglyLinkedNode<T> n) {
this.next = n;
}
//...
}
我很感激你能提供的任何帮助。提前致谢!
编辑:感谢您的帮助!我已经从我的方法中删除了,但是当我从我的 SinglyLinkedList 类运行 setNext() 时我仍然收到以下错误:
.\singlyLinkedList\SinglyLinkedList.java:63: error: method setNext in class SinglyLinkedNode<T#2> cannot be applied to given types;
curr.setNext() = toBeRemoved.getNext();
^
required: SinglyLinkedNode<T#1>
found: no arguments
reason: actual and formal argument lists differ in length
where T#1,T#2 are type-variables:
T#1 extends Object declared in class SinglyLinkedList
T#2 extends Object declared in class SinglyLinkedNode
.\singlyLinkedList\SinglyLinkedList.java:79: error: method setNext in class SinglyLinkedNode<T#2> cannot be applied to given types;
prev.setNext() = this.head;
^
所以在看来,getNext()(来自 SinglyLinkedNode)和 head(来自 SinglyLinkedList)没有返回任何值,即使它们都应该返回 SinglyLinkedNode 对象。
侃侃尔雅
陪伴而非守候
相关分类