2015-05-17 17 views
1
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 { 

    } 

} 

這是我的代碼,並由於某種原因,它與我做奇怪的錯誤,試圖在java中創建一個通用的鏈表類

head = node; 

它說一個問題:

Type mismatch: cannot convert from GenericListNode<T> to GenericListNode <T extends Comparable<T>> 

它建議鑄造節點是

head = (GenericListNode<T>) node; 

乙它仍然給我的錯誤。

+2

你覺得什麼'T'在'公共無效add'呢? –

+0

你的類GenericListNode看起來如何 –

回答

4

在此聲明

public <T> void add 

要定義一個新的類型,稱爲T這是在類級別定義的T完全獨立的。這是聲明一個通用方法的符號。

由於兩種類型不具有相同的邊界,因此它們不兼容,無法將其轉換爲另一種。

擺脫那個泛型聲明。

3

不要在你的方法重新定義T

public void add (int index, T toAdd) { 
    GenericListNode<T> node = new GenericListNode<T>((T) toAdd); 
    if (isEmpty()) { 
     head = node; 
    } else { 

    } 
} 

T在「類級」已經被定義,如果你對你是隱藏的類一級的方法再次添加它,所以你有兩種不同的類型,稱爲T

2

您正在重新定義(讀取:陰影)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 { 

     } 
    } 
}