[英]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.