2015-03-31 116 views
-2

什麼關鍵是最好的HashMap?我應該使用什麼鍵爲HashMap?

  1. 我只用了十進制,每個鍵都是以前的++,但這只是我的想法,我不知道它是否有效。

  2. 我讀到了hashCode,這個值通常用於散列表,但人們說不要濫用hashCode()作爲關鍵字。

等待您的答案和資源鏈接。 這裏的代碼片段:

Identifier identifier = new Identifier(); 
identifier.setName(getString(currentToken)); 
identifier.setLine(currentLineNumber); 
int key = identifier.hashCode(); 
tableOfIdentifiers.put(key, identifier); 
+2

爲什麼不直接使用標識符?引入哈希映射的原因是什麼? – aioobe 2015-03-31 09:08:02

+0

爲什麼你使用散列碼作爲地圖中的鍵?請注意,散列碼通常不是唯一的,所以這可能會導致問題。 – Jesper 2015-03-31 09:32:02

回答

1

這是極爲罕見的用戶代碼直接調用hashCodehashCode方法自定義對象實現之外。特別是在您的情況下,呼叫是不必要的,因爲HashMapHashSet依靠內部呼叫hashCode

從你的例子看,你不需要HashMap:a HashSet應該足夠了。

private Set<Identifier> tableOfIdentifiers = new HashSet<Identifier>(); 
... 
if (!tableOfIdentifiers.add(identifier)) { 
    ... // Duplicate identifier is detected 
} 
0

理想情況下,映射用於具有一些鍵值對。鑰匙應該是唯一的,可以理解的。地圖可能具有不同密鑰的重複值,但如果使用哈希碼作爲密鑰,地圖將覆蓋您以前的值。嘗試使用邏輯名稱作爲鍵。可以是empcode,studentRollNumber等。

相關問題