我正在测试TreeMap
的行为并了解排序过程。然而,我仍然困惑的想法是,对于检索,自定义键类需要重写hashCode方法。说了这么多,我已经搜索了足够的谷歌,但找不到任何合理的答案。我们是否需要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);
}
}
试验规程试验树状图..
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文档。
TreeMap绝对不会调用'hashCode' ---除非你通过调用'TreeMap#hashCode()'强制它。 – 2014-09-06 16:14:43
树不是散列表。没有必要计算哈希值。 – 2014-09-06 16:15:49
请仔细阅读TreeMap的文档。它需要一个实现Comparable接口的类或一个传递给它的构造函数的Comparator。它只调用这些接口的实现 – 2014-09-06 16:16:10