【问题标题】:What keys should I use for HashMap?我应该为 HashMap 使用哪些键?
【发布时间】:2015-03-31 09:04:29
【问题描述】:

什么键最适合 HashMap?

  1. 我只使用了十进制,每个键都是previous++,但这只是我的想法,我不知道它是否有效。

  2. 我读到了 hashCode,这个值通常用于哈希表,但人们说不要误用 hashCode() 作为键。

等待您的答案和资源链接。 这是代码sn-p:

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

【问题讨论】:

  • 为什么不直接使用标识符呢?引入哈希映射的原因是什么?
  • 为什么在map中使用哈希码作为key?请注意,哈希码通常不是唯一的,因此可能会导致问题。

标签: java hash hashtable


【解决方案1】:

用户代码在自定义对象的hashCode 方法的实现之外直接调用hashCode 是非常罕见的。特别是,在您的情况下,调用是不必要的,因为 HashMapHashSet 依赖于内部调用 hashCode

从您的示例来看,您似乎不需要HashMapHashSet 应该就足够了。

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

【讨论】:

    【解决方案2】:

    理想情况下,映射用于具有一些键值对。键应该是唯一且易于理解的。映射可能具有不同键的重复值,但如果使用哈希码作为键,映射将覆盖您以前的值。尝试使用逻辑名称作为键。可以是 empcode、studentRollNumber 等。

    【讨论】:

      猜你喜欢
      • 2017-08-11
      • 2014-04-21
      • 2011-11-21
      • 1970-01-01
      • 2010-11-26
      • 2018-06-21
      • 2012-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多