2015-03-31 148 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等。

相关问题