2009-06-06 61 views
5

我用(key:String,value:ArrayList)將數據存儲在HashMap中。我遇到的部分聲明一個新的ArrayList「current」,在HashMap中搜索字符串「dictCode」,如果找到,則將當前設置爲返回值ArrayList。HashMap(key:String,value:ArrayList)返回一個Object而不是ArrayList?

ArrayList current = new ArrayList();  
if(dictMap.containsKey(dictCode)) { 
    current = dictMap.get(dictCode); 
} 

「當前= ...」行返回的編譯器錯誤:

Error: incompatible types 
found : java.lang.Object 
required: java.util.ArrayList 

我不明白這...這是否HashMap中返回一個對象,而不是ArrayList中的我存儲在它作爲價值?如何將此對象轉換爲ArrayList?

謝謝。

+0

添加HashMap聲明來澄清問題。 – Jorn 2009-06-06 23:41:44

回答

33

如何在該範圍內表示HashMap聲明?它應該是:

HashMap<String, ArrayList> dictMap 

如果不是,則假定爲對象。

舉例來說,如果你的代碼是:

HashMap dictMap = new HashMap<String, ArrayList>(); 
... 
ArrayList current = dictMap.get(dictCode); 

這是行不通的。相反,你想:

HashMap<String, ArrayList> dictMap = new HashMap<String, Arraylist>(); 
... 
ArrayList current = dictMap.get(dictCode); 

的方式仿製藥的工作是該類型的信息是提供給編譯器,而不是在運行時可用。這被稱爲類型擦除。 HashMap(或任何其他泛型實現)的實現正在處理Object。類型信息在編譯期間用於類型安全檢查。請參閱Generics documentation

另請注意,ArrayList也作爲泛型類實現,因此您可能也希望在其中指定類型。假設你ArrayList包含您MyClass類,上面的行可能是:

HashMap<String, ArrayList<MyClass>> dictMap 
2

我想你dictMap是HashMap型的,這使得它默認爲HashMap<Object, Object>。如果你想要它更具體,可以聲明它爲HashMap<String, ArrayList>,或者更好,因爲HashMap<String, ArrayList<T>>

+0

謝謝... ArrayList >位是做什麼的? – cksubs 2009-06-06 23:49:21

2

使用泛型(如上面的答案)是你最好的選擇。我只是雙重檢查和:

test.put("test", arraylistone); 
    ArrayList current = new ArrayList(); 
    current = (ArrayList) test.get("test"); 

也能發揮作用,通過我不會推薦它作爲泛型保證只有正確的數據添加,而不是試圖在檢索的時候做處理。

2

HashMapget方法返回一個Object,但可變current預計需要一個ArrayList

ArrayList current = new ArrayList(); 
// ... 
current = dictMap.get(dictCode); 

對於上面的代碼工作,Object必須強制轉換爲ArrayList

ArrayList current = new ArrayList(); 
// ... 
current = (ArrayList)dictMap.get(dictCode); 

但是,可能更好的方法是首先使用泛型集合對象:

HashMap<String, ArrayList<Object>> dictMap = 
    new HashMap<String, ArrayList<Object>>(); 

// Populate the HashMap. 

ArrayList<Object> current = new ArrayList<Object>();  
if(dictMap.containsKey(dictCode)) { 
    current = dictMap.get(dictCode); 
} 

上述代碼被假定ArrayList具有Object秒的列表,並且應該根據需要改變。

有關泛型的更多信息,Java教程有lesson on generics

10
public static void main(String arg[]) 
{ 
    HashMap<String, ArrayList<String>> hashmap = 
     new HashMap<String, ArrayList<String>>(); 
    ArrayList<String> arraylist = new ArrayList<String>(); 
    arraylist.add("Hello"); 
    arraylist.add("World."); 
    hashmap.put("my key", arraylist); 
    arraylist = hashmap.get("not inserted"); 
    System.out.println(arraylist); 
    arraylist = hashmap.get("my key"); 
    System.out.println(arraylist); 
} 

null 
[Hello, World.] 

工作正常......也許你在我的代碼中發現你的錯誤。

相關問題