1. 源起 有的時候資料對象經常會放到HashMap或者HashSet裡面,希望根據ID來表示資料對象,這就需要覆蓋hashCode和equals方法。
2. 代碼
public class Goods { public Goods(int id) { this.id = id; } public int id; public String name; public String image; public double price; public static void main(String[] args) { Set<Goods> set = new HashSet<Goods>(); Goods a = new Goods(0); Goods b = new Goods(0); set.add(a); set.add(b); HashMap<Goods, Integer> map = new HashMap<Goods, Integer>(); map.put(a, 0); map.put(b, 0); System.out.println("Goods"); System.out.println("set num = " + set.size()); System.out.println("map key set num = " + map.keySet().size()); System.out.println("a.hashCode() = " + a.hashCode()); System.out.println("b.hashCode() = " + b.hashCode()); }};
Goods set num = 2 map key set num = 2 沒有重載的時候,即使ID相同,也被當作兩個對象。
public class GoodsWithHashAndEquals { public GoodsWithHashAndEquals(int id) { this.id = id; } public int id; public String name; public String image; public double price; @Override public int hashCode() { return id; } @Override public boolean equals(Object obj) { return obj.hashCode() == hashCode(); } public static void main(String[] args) { Set<GoodsWithHashAndEquals> set = new HashSet<GoodsWithHashAndEquals>(); GoodsWithHashAndEquals a = new GoodsWithHashAndEquals(0); GoodsWithHashAndEquals b = new GoodsWithHashAndEquals(0); set.add(a); set.add(b); HashMap<GoodsWithHashAndEquals, Integer> map = new HashMap<GoodsWithHashAndEquals, Integer>(); map.put(a, 0); map.put(b, 0); System.out.println("GoodsWithHashAndEquals"); System.out.println("set num = " + set.size()); System.out.println("map key set num = " + map.keySet().size()); System.out.println("a.hashCode() = " + a.hashCode()); System.out.println("b.hashCode() = " + b.hashCode()); }}
GoodsWithHashAndEquals set num = 1 map key set num = 1 重載後,ID相同,就是被當做一個對象了。
3. 參考 Map的HashCode做緩衝key值引發的重大bug JAVA中的equals()和hashCode()方法
4. 本文連結 http://blog.csdn.net/xiaodongrush/article/details/9419831