[Valid Java] 5. overwrite the hashcode and mongoshashcode when overwriting equals.
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) area Code; 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 to why 31 is used, this is the recommended value. Studies have shown that this number provides better performance in 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 the overhead is large, you need to take the test. The hash code is cached inside the object // The variable modified with volatile. Every time a thread uses a variable, it reads the modified value of 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,530 9), "Jenny"); // jenny is not returned here, and null is returned, this is because put objects are put in different hash buckets. out. println (m. get (new PhoneNumber (707,867,530 9 )));}}