2013-05-10 58 views
1

,所以我有這四個類/接口:添加一個通用的ArrayList到一個ArrayList

public class Box <S extends SomeClass> implements Comparable <Box<S>> {...} 
    public interface SomeClass <T extends Comparable<T>> {...} 
    public class ThisItem implements SomeClass {...} 
    public class OtherItem implements SomeClass {...} 

,我試圖創建一個擁有ThisItem的實例的列表框中的列表。我不確定爲什麼這會給我一個錯誤。

public ArrayList<ArrayList<Box>> variable = new ArrayList<ArrayList<Box>>(); 
    this.variable.add(new ArrayList<Box<ThisItem>>(5)); 
+2

確保包括在問題*確切*錯誤消息。 – user2246674 2013-05-10 00:17:45

+1

這僅僅是我還是有時候人們只是泛泛而談呢? – 2013-05-10 00:22:40

回答

5

Box是一個通用的類,因此當使用它就像Box,它是一個原始類型,它是從Box<ThisItem>,其具有指定的類型的參數不同。這與ArrayList<Box>類似,其中Box它是類型參數。

更改此:

public ArrayList<ArrayList<Box>> variable = new ArrayList<ArrayList<Box>>(); 

到:

public ArrayList<ArrayList<Box<ThisItem>>> variable = new ArrayList<ArrayList<Box<ThisItem>>>(); 
+0

這擺脫了錯誤,但是我需要實例化ArrayList,然後在一個新類的構造函數中添加ThisItem或OtherItem ArrayList,以便我可以將它們各自類型的項添加到它。 – TheGandhi 2013-05-10 00:38:03

1

ThisItem原料類型的SomeClass;它與將其聲明爲implements SomeClass<Object>大致相同,因此編譯器無法驗證以這種方式使用它是否合適。

相反,聲明爲類型:

public class ThisItem implements SomeClass<SomeComparableClass> {...} 
+0

我不太清楚的含義。你能解釋一下嗎? – TheGandhi 2013-05-10 00:49:54

+0

SomeClass被定義爲'public interface SomeClass >',這意味着要實現它是一個'typed'接口(不是* raw *類型),您必須爲泛型參數提供一個類型,並且該類型爲以Comparable類型爲界,所以SomethingComparable就是這種類型。我將改變它的名字然後 - 編輯 – Bohemian 2013-05-10 02:44:29

0

怎麼樣這個..

public ArrayList<ArrayList<Box>> variable = new ArrayList<ArrayList<Box>>(); 
this.variable.add(new ArrayList<Box<ThisItem>>(5)); 

到...

public ArrayList<ArrayList<Box>> variable = new ArrayList<ArrayList<Box>>(); 
ArrayList<Box<ThisItem>> tempInstance = new ArrayList<>(); 
tempInstance.add(new Box<ThisItem>()); //add new Boxes manually as you wish 
this.variable.add(tempInstance); 
+0

出現錯誤,「無法將ArrayList 轉換爲ArrayList >」 – TheGandhi 2013-05-10 00:44:04

1

你怎麼想,這將是安全的variable店鋪列表如ArrayList<Box<ThisItem>>

如果Java會讓這種情況發生,那麼從variable獲得該列表時,它將被加載到ArrayList<Box>。因爲返回的列表會讓你添加任何種類的Box對象到最初的列表ArrayList<Box<ThisItem>>假設只存儲Box<ThisItem>對象。

爲了擺脫這個問題,你應該聲明你variable作爲

public ArrayList<ArrayList<Box<ThisItem>>> variable 
= new ArrayList<ArrayList<Box<ThisItem>>>(); 
+0

問題是我不知道該框是否需要鍵入ThisItem或OtherItem,直到我進入需要arraylist的構造函數。那麼有沒有辦法在構造函數w.o中創建一個實例變量來定義它之外的變量? – TheGandhi 2013-05-10 00:48:48

+0

@TheGandhi這個錯誤的目的是阻止你在我的答案中描述的情況,但是如果你確定你不會將不正確的對象添加到不正確的列表中,你可以通過將你的新列表轉換爲原始類型來擺脫這個錯誤'variable.add((ArrayList)new ArrayList >(5));'。但是這種編碼方式對於類型安全是危險的,所以除非你沒有其他選擇,否則不要使用它(大多數情況下,人們可以重新設計他們的項目以避免這種情況)。 – Pshemo 2013-05-10 01:28:29

0

這應該工作:

public ArrayList<ArrayList<? extends Box>> variable = new ArrayList<ArrayList<? extends Box>>(); 
相關問題