2014-02-26 30 views
1

我想創建一個LinkedMap其關鍵是Map類型的太像這樣:是否可以創建類型映射圖的鍵?

LinkedHashMap<LinkedHashMap<String, Float>, String> map = 
     new LinkedHashMap <LinkedHashMap<String, Float>, String> 

是否有可能或不?如果是的話:我怎樣才能調用Map Key的Keys和Values?

+1

什麼是與嘗試這一問題呢? – Maroun

+0

是的,你可以做到這一點。因爲它期望鑰匙是對象。 – Rahul

+0

如果它編譯,這是可能的 - >主要的java祕密>) – injecteer

回答

1

是的,你可以做到這一點。

LinkedHashMap<LinkedHashMap<String, Float>, String> map = new LinkedHashMap<>();(Java 7的符號)

但正如你在地圖中鍵是地圖,你將是真的很難訪問它,你將需要提供最有可能同一個實例只檢索字符串值。而調試也將非常困難。

您可能想嘗試創建一個類,該類將存儲以地圖形式存儲的數據,並編寫適當的hashcode()equals()實現,以簡化代碼。

5

如果你有Map這需要另一個Map作爲重點,那麼你將有一個不穩定的Map,因爲從任何Maps,你正在使用的密鑰會改變他們的哈希碼添加或刪除鍵/值。所以,你應該從不做到這一點。密鑰不應該有變化的哈希碼!

+0

但我需要註冊信息<句子,分數>在第一類中比我應該在第二類中使用它們更加節省每個實例<句子,分數>其他標準,沒有其他解決方案。 – MalakTN

+0

如果您可以100%保證您的地圖的哈希碼永遠不會改變,那麼你可以做到這一點,但我強烈建議反對它沒有這種保證......總有辦法做到這一點,它可能不會那麼快,這可能無關緊要你的特定問題。 –

1

理論上,你可以做到這一點。 java編譯器不會抱怨任何事情。

但實際上,建議不要使用其hashCode()可更新的任何對象作爲密鑰。原因是當對條目進行散列操作並查找某個鍵時,該鍵的hashCode將被LinkedHashMap使用(實際上,它是它的超類HashMap)。

爲了更好地理解,你會滿足使用的代碼如下問題:

LinkedHashMap<Map<String, Integer>, String> map = new LinkedHashMap<>(); 
Map<String, Integer> key1 = new HashMap<>(); 
key1.put("one", 1); 
map.put(key1, "value associated with key1"); 

// this would print: true 
System.out.println(map.containsKey(key1)); 

key1.put("two", 2); 

// after previous statement, the map key1 has a new hashCode() 

// this would print: false 
// The reason is: the hashCode() method of HashMap is based on all 
// the entries it contains. Since previous key1.put("two", 2) 
// cause a new entry added into the map, thus the hashCode() of 
// key1 has changed. In the meantime, the LinkedHashMap didn't 
// rehash which means the key1 is still hashed using the old 
// hashCode. This furthur lead to the LinkedHashMap.containsKey() 
// cannot find the key1 by comparing the new hashCode and the old 
// one 
System.out.println(map.containsKey(key1)); 
相關問題