我正在測試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