【发布时间】: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