2012-09-22 62 views
-2

爲什麼我在我的代碼在我的課ArrayListTest最終得到一個編譯時錯誤兩種方法頭?的ArrayList在Java中,將代碼添加到方法

ArrayListTest:http://pastebin.com/dUHn9vPr

學生:http://pastebin.com/3Vz1Aytr

我有兩行編譯器錯誤:

delete(CS242, s3) 

replace(CS242, s, s4); 

當我嘗試運行代碼時指出:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
    The method replace(ArrayList<Student>, Student, Student)in the type ArrayListTest is not applicable for the arguments (List<Student>, Student, Student) 
    The method delete(ArrayList<Student>, Student) in the type ArrayListTest is not applicable for the arguments (List<Student>, Student) 
     at ArrayListTest.main(ArrayListTest.java:54) 

我修復了編譯時錯誤,因爲我使用Eclips e和Eclipse提供了可用於修復編譯時錯誤的代碼選項。我選擇了「將方法更改爲'(ArrayList,Student,Student)'替換爲'List(學生,學生)'

雖然它修復了編譯時錯誤,但我不明白爲什麼我得到編譯時錯誤開始,爲什麼能夠有效地固定錯誤

我真的不知道缺少什麼代碼,我需要寫更正以下兩種方法:

public static void replace(List<Student> cS242, Student oldItem, 
       Student newItem) { 

public static void delete(List<Student> cS242, Student target){ 
+0

這些錯誤是非常明顯的,方法聲明中的類型與您所調用的方法不匹配。 – Borgleader

+0

閱讀泛型中的繼承。 – kosa

+3

您應該在問題中包含ArrayListTest類的摘錄。由於pastebin內容是外部的,如果缺失可能會導致問題不合格。實際上它現在在23小時後過期。 – Javier

回答

0

在粘貼的代碼中,兩種方法replacedelete不會更改爲List<Student>。這是導致編譯錯誤的原因秒。

他們在那裏擺在首位,因爲在第9行,你正在創建一個ArrayList,並將其保存在一個List變量。這很好,因爲ArrayList實現了List,所以每個ArrayList也是一個List。稍後,您嘗試調用需要ArrayList作爲參數的函數。雖然這個特定的List也是一個ArrayList(因爲您使用了ArrayList構造函數),但這並不適用於所有列表。所以你必須明確地強制轉換或將它保存爲ArrayList。

0

方法public static void replace(ArrayList<Student> aList, Student oldItem, Student newItem)將不允許List<Student>列表類型,以進行傳遞。

換句話說,第一個參數需要是一個ArrayList(或亞類)。當您將簽名更改爲public static void replace(List<Student> aList, Student oldItem, Student newItem)時,類型List<Student>的參數CS242與預期的參數類型匹配。

2

那是因爲你宣佈你的ArrayList<Student>爲:

List<Student> CS242 = new ArrayList<Student>(25); 

而且你replace方法:

public static void replace(ArrayList<Student> aList, Student oldItem, Student newItem) { 
} 

對於Java,要傳遞的東西是一個List一種方法是將只與ArrayList s一起工作。 如果它允許你這樣做,你可以舉例來說,實施更改爲LinkedList<Student>,仍然把它傳遞給replace這將是不正確的。

既可以使用replace(List<Student>),也可以聲明CS242ArrayList<Student> CS242,雖然前者被認爲是最佳做法。