[英]weird error, trying to create a generic linked list class in java
public class GenericLinkedList<T extends Comparable<T>> implements Cloneable {
GenericListNode<T> head;
/**
* inserts a new node containing the data toAdd at the given index.
* @param index
* @param toAdd
*/
public <T> void add (int index, T toAdd) {
GenericListNode<T> node = new GenericListNode<T>((T) toAdd);
if (isEmpty()) {
head = node;
} else {
}
}
这是我的代码,由于某种原因,我在执行时遇到了问题
head = node;
它说:
Type mismatch: cannot convert from GenericListNode<T> to GenericListNode <T extends Comparable<T>>
建议将Casting节点设置为
head = (GenericListNode<T>) node;
但这仍然给我错误。
在此声明中
public <T> void add
您正在定义一个称为T
的新类型,该类型与在类级别定义的T
完全独立。 这就是声明通用方法的表示法。
由于这两种类型没有相同的界限,因此它们不兼容,并且一种不能转换为另一种。
摆脱通用声明。
不要在您的方法中重新定义T
:
public void add (int index, T toAdd) {
GenericListNode<T> node = new GenericListNode<T>((T) toAdd);
if (isEmpty()) {
head = node;
} else {
}
}
T
已经在“类级别”定义了,如果您再次将其添加到隐藏类级别的方法上,则将有两种不同的类型称为T
您正在重新定义(阅读:阴影) T
的一般定义。 只需将其从方法定义中删除,就可以了:
public class GenericLinkedList<T extends Comparable<T>> implements Cloneable {
GenericListNode<T> head;
/**
* inserts a new node containing the data toAdd at the given index.
* @param index
* @param toAdd
*/
public void add (int index, T toAdd) {
GenericListNode<T> node = new GenericListNode<T>(toAdd);
if (isEmpty()) {
head = node;
} else {
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.