【问题标题】:Do we need hashCode Implementation for TreeMap?我们需要 TreeMap 的 hashCode 实现吗?
【发布时间】:2014-09-06 16:13:08
【问题描述】:

我正在测试TreeMap 的行为并了解排序的过程。但是,我仍然感到困惑的是,对于检索,自定义键类是否需要覆盖 hashCode 方法。话虽如此,我已经搜索了足够多的谷歌,但找不到任何合理的答案。

以下是我使用的示例。

class Dog implements Comparable<Dog> {
    String color;
    int size;

Dog(String c, int s) {
    color = c;
    size = s;
 }

int hc;

@Override
public int hashCode() {
    hc = super.hashCode();
    return hc;
}

@Override
public int compareTo(Dog o) {
    return this.color.compareTo(o.color);
}
}

测试 TreeMap 的测试代码..

public class TestHashMap {
    public static void main(String[] args) {
        Dog d1 = new Dog("a", 1);
        Dog d2 = new Dog("b", 2);
        Dog d3 = new Dog("c", 3);
        Dog d4 = new Dog("d", 4);
        Dog d5 = new Dog("e", 5);

        Dog d = new Dog("c", 3);

        TreeMap<Dog, Integer> hm = new TreeMap<>();
        hm.put(d1, 10);
        hm.put(d2, 15);
        hm.put(d3, 5);
        hm.put(d4, 20);
        hm.put(d5, 25);

        System.out.println("value is :" + hm.get(d));
    }
}

不管我是否实现了 hashCode 方法,值是否被正确检索,但是在调试时,总是调用 hashcode 方法,所以如果真的 hashCode 实现是强制性的,我会感到困惑。

谁能帮助理解从 TreeMap 检索的正确行为。

请不要从 TreeMap 复制粘贴 java doc。

【问题讨论】:

  • TreeMap 绝对不会调用hashCode---除非你通过调用TreeMap#hashCode() 来强制它。
  • 树不是哈希表。无需计算哈希。
  • 请浏览 TreeMap 的文档。它需要一个实现 Comparable 接口的类或传递给它的构造函数的 Comparator。它只调用这些接口的实现
  • hashCode 中的断点被触发时,您是否检查过实际的堆栈跟踪? hashCode的直接调用者是哪个方法?
  • @MarkoTopolnik :非常抱歉造成混淆。我在 sysout 中调用 hashcode 方法因此感到困惑。为混淆道歉

标签: java dictionary hashcode treemap comparable


【解决方案1】:

hashCode() 被称为默认toString() 实现的一部分。由于您还没有实现自己的toString(),我怀疑您在代码中的某处打印了Dog,导致方法调用。

【讨论】:

  • 打印出来的hm.get(d)Integer,而不是Dog
  • @Danstahr。 : 是的,你是对的,我也犯了同样的错误。
【解决方案2】:

我发现 这是我的错误,我在 toString() 方法中显式调用 hashCode() 造成了这种混乱。

但结论是,对于TreeMap,它遵循Comparable Interface实现,不遵循hashCode和equals实现。

【讨论】:

  • 也许您的调试器正在调用toString()hashCode() 结果?我在 IntelliJ 中调试您的代码,但执行从未在 Dog.hashCode() 的断点处停止。或者,也许您运行的代码与您发布的不同。
  • 是的,发布的代码没有它。这是我的代码,我错过了 System.out.println 复制。
  • 但请注意,It is strongly recommended (though not required) that natural orderings be consistent with equals. This is so because sorted sets (and sorted maps) without explicit comparators behave "strangely" when they are used with elements (or keys) whose natural ordering is inconsistent with equals. In particular, such a sorted set (or sorted map) violates the general contract for set (or map), which is defined in terms of the equals method.---并且,无论何时覆盖 equals,您必须覆盖 hashCode 以匹配。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-07
  • 2012-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-06
相关资源
最近更新 更多