package com.hash; import java.util.HashMap; public class Apple { private String color; public Apple(String color) { this.color = color; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((color == null) ? 0 : color.hashCode()); return result; } public boolean equals(Object obj) { if (!(obj instanceof Apple)) return false; if (obj == this) return true; return this.color == ((Apple) obj).color; } public static void main(String[] args) { Apple a1 = new Apple("green"); Apple a2 = new Apple("red"); //hashMap stores apple type and its quantity HashMap<Apple, Integer> m = new HashMap<Apple, Integer>(); m.put(a1, 10); m.put(a2, 20); System.out.println(m.get(new Apple("green"))); } }
從上文代碼不難看出,HashMap已保存一個"green"的Apple對象,但是,,在執行時,會發生一個問題,,,用map獲取"Apple"對象時,並未找到。
然而,為什么會造成這問題呢,,,這就是本文主旨所在。
---是由於hashCode()引起,因為沒有重寫hashCode()方法.
equals()方法與hashCode()方法的隱式調用時的約定是:
1.如果兩個對象相等(equals),那么他們必須擁有相同的哈希嗎(hashCode)
2.即使兩個對象擁有相同的hashCode,他們也不一定相等.
Map的核心思想就是可以比線性查找更快. 通過散列值(hash)作為鍵(key)來定位對象的過程分為兩步:
在Map內部,存儲着一個頂層數組,頂層數組的每個元素指向其他的數組,查找或存儲的時候,先根據key對象的hashCode()值計算出數組的索引,然后到這個索引找到所指向的第二層線性數組,使用equals方法來比較是否有相應的值(以返回或者存儲).
Object類中的hashCode()默認為每個對象返回不同的int值,因此在上面的例子中,兩個相等(equal)的對象,返回了不同的hashCode值.
解決方法是為此類添加hashCode方法,比如,使用color字符串的長度作為示范:
在Map內部,存儲着一個頂層數組,頂層數組的每個元素指向其他的數組,查找或存儲的時候,先根據key對象的hashCode()值計算出數組的索引,然后到這個索引找到所指向的第二層線性數組,使用equals方法來比較是否有相應的值(以返回或者存儲).
Object類中的hashCode()默認為每個對象返回不同的int值,因此在上面的例子中,兩個相等(equal)的對象,返回了不同的hashCode值.
解決方法是為此類添加hashCode方法,比如,使用color字符串的長度作為示范:
public int hashCode(){ // 此種實現,要求 color值定以后就不得修改 // 否則同一個物理對象,前后有兩個不同的hashCode,邏輯上就是錯的。 return this.color.length(); }
參考地址:http://www.acfun.tv/a/ac1876770