2015-05-07 44 views
1

大家好今天我試圖在我的ArrayList中做這個,我知道這是可能的,但它給了我一個主要的例外。現在我想知道我怎麼做錯了,或者最好的辦法是什麼。我試圖擁有一個ArrayList,並在ArrayList中有另一個,我給它一個變量。擁有多個ArrayList

import java.util.ArrayList; 
import java.util.Collection; 

public class Example3 { 
public static void main(String[] args) { 
    ArrayList<ArrayList<Family>> smallFamily = new ArrayList<ArrayList<Family>>(); 
    smallFamily.addAll((Collection<? extends ArrayList<Family>>) (new Family("John",89))); 

    smallFamily.addAll((Collection<? extends ArrayList<Family>>) new Family ("Smith", 78))); 

    for(ArrayList<Family> s: smallFamily){ 
     System.out.println(s); 
    } 

} 

現在吼叫是我的家庭團聚類和我的家庭這是

public class Family { 

    public String Name; 
    public int weight; 

    public Family(String Name, int weight){ 
     this.Name = Name; 
     this.weight = weight; 
    } 
    public String toString(){ 
     return ("The name is " + this.Name + "The weight is: " + this.weight); 
    } 
}} 

當我編譯和運行我的程序將引發異常值是

Exception in thread "main" java.lang.ClassCastException: Examples.Family cannot be cast to java.util.Collection 
    at Examples.Example3.main(Example3.java:9) 

現在學習Java本身並沒有任何人可以問。任何形式的幫助將不勝感激。

+2

您在'new Family(「Smith」,78)'之前忘記了'('在第二個'smallFamily.addAll'行上。' – krillgar

+0

只需要注意一點,不要讓變量字符串名稱,int weight public, –

+0

對不起,可能是在打字,但在我的程序中很清楚 – KIM

回答

2

您正試圖將對象轉換爲集合。這不起作用。相反,你需要做的是:

smallFamily.add(new ArrayList<Family>(1) {{add(new Family("", 0));}}); 

這將創建一個ArrayList創建時,它增加了new Family("", 0)。然後,它會將此數組列表添加到小家族數組列表中。現在

+0

讓我看看 – KIM

+0

嘿,謝謝,這是一個很好的解釋。 – KIM

+0

請注意,'arraylist'的大小爲'1',以便數組列表不必增加其大小,這需要大量計算 – HyperNeutrino

0

爲什麼你在這裏得到這條線

smallFamily.addAll((Collection<? extends ArrayList<Family>>) (new Family("John",89))); 

僅僅是因爲計算機不可能瞭解你在做什麼,從而鑄造了你。或者你鑄造:)。現在試圖將對象轉換爲集合不起作用。

而是你需要時,你把你的家庭團聚類

public class Family { 

    public String Name; 
    public int weight; 

    public Family(String Name, int weight){ 
     this.Name = Name; 
     this.weight = weight; 
    } 
    public String toString(){ 
     return ("The name is " + this.Name + "The weight is: " + this.weight); 
    } 
} 

嘗試這種

public class Example3 { 
public static void main(String[] args) { 
    ArrayList<ArrayList<Family>> smallFamily = new ArrayList<ArrayList<Family>>(); 
    smallFamily.add(new ArrayList<Family>(2222) {{add(new Family("smith ", 0));}}); 

    smallFamily.add(new ArrayList<Family>(333) {{add(new Family("john ", 0));}}); 

    for(ArrayList<Family> s: smallFamily){ 
     System.out.println(s); 
    } 

} 
} 

輸出應該

[The name is smith The weight is: 0] 
[The name is john The weight is: 0] 

希望這是你的預期是什麼。