Java always overwrite hashcode when overwriting equals
Recently, I have learned the basic knowledge of Java. When I encounter Java covering equals, I always have many questions when I have to overwrite hashcode. After directly discussing with my colleagues and querying the information online, I will sort it out here to help everyone understand it and there are instructions in the code.
Specific implementation code:
package cn.xf.cp.ch02.item9;import java.util.HashMap;import java.util.Map;public class PhoneNumber{ private final short areaCode; private final short prefix; private final short lineNumber; public PhoneNumber(int areaCode, int prefix, int lineNumber) { rangeCheck(areaCode, 999, "area code"); rangeCheck(prefix, 999, "prefix"); rangeCheck(lineNumber, 9999, "line number"); this.areaCode = (short) areaCode; this.prefix = (short) prefix; this.lineNumber = (short) lineNumber; } private static void rangeCheck(int arg, int max, String name) { if (arg < 0 || arg > max) throw new IllegalArgumentException(name + ": " + arg); } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof PhoneNumber)) return false; PhoneNumber pn = (PhoneNumber) o; return pn.lineNumber == lineNumber && pn.prefix == prefix && pn.areaCode == areaCode; } /* @Override //As for why 31 is used, this is the recommended value. Studies have shown that this number performs better when used public int hashCode() { int result = 17; result = 31 * result + areaCode; result = 31 * result + prefix; result = 31 * result + lineNumber; return result; } */ //If an object does not change frequently and has a high overhead, you should consider the hash code cache inside the object//Variables modified with volatile, the thread will read the most modified value of the variable every time it uses the variable. private volatile int hashcode; @Override public int hashCode() { int result = hashcode; if (result == 0) { result = 17; result = 31 * result + areaCode; result = 31 * result + prefix; result = 31 * result + lineNumber; hashcode = result; } return result; } public static void main(String[] args) { Map<PhoneNumber, String> m = new HashMap<PhoneNumber, String>(); m.put(new PhoneNumber(707, 867, 5309), "Jenny"); //Jenny will not be returned here, it will return null, because they put objects in different hash buckets System.out.println(m.get(new PhoneNumber(707, 867, 5309))); }}Thank you for reading, I hope it can help you. Thank you for your support for this site!