1. SourceSometimes, data objects are often stored in hashmap or hashset, and you want to represent data objects by ID. This overwrites the hashcode and equals methods.
2. Code
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()); }};When goods set num = 2 Map key set num = 2 is not overloaded, it is treated as two objects even if the IDs are the same.
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()); }}After goodswithhashandequals set num = 1 Map key set num = 1 is overloaded, the IDs are the same and are treated as an object.
3. ReferenceMajor bugs caused by cached key values in map hashcode: equals () and hashcode () methods in Java
4. Link to this articleHttp://blog.csdn.net/xiaodongrush/article/details/9419831