2013-12-14 25 views
0

今天,我遇到了Java 7泛型數組創建的奇怪情況。請看下面的兩條語句。通過鑽石算子創建通用數組

Map<String, String>[] hashArr= new HashMap[2]; // Compiles 

Map<String, String>[] hashArr= new HashMap<>[2];// Does not compile 

這裏首先聲明編譯沒有鑽石運營商,如果我把鑽石運營商或通用型的右側比它不會編譯。我面臨所有類型的相同情況,List<T>Set<T>

誰能告訴我,什麼是不編譯第二條語句的原因?

+0

@Downvoter,請發表評論,這是什麼問題的錯誤? – Masudul

+0

因爲你不能創建一個'HashMap'類型的泛型數組。 –

+0

@ElliottFrisch,我可以用第一個語句創建數組。 – Masudul

回答

2

由於類型擦除(通用(s)被編譯步驟擦除),您不能在java中創建類型爲HashMap的通用數組。此代碼

Map<String, String>[] hashArr= new HashMap<String,String>[2]; // gives a better error. 

你的第一條語句是類型化HashMap數組,我知道它編譯。它工作嗎?

要我高興,這確實工作

Map<String, String>[] hashArr = new HashMap[1]; 
hashArr[0] = new HashMap<>();     // Your diamond sir. 
hashArr[0].put("Hello", "World"); 
System.out.println(hashArr[0].get("Hello"));