Always overwrite hashcode when Java overrides equals
Recent Learning Java Basics, encounter Java coverage equals always have to cover hashcode when there are many questions, and colleagues directly discussed and online inquiry information, here to tidy up, or help you understand, the code has instructions.
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 n
EW illegalargumentexception (name + ":" + arg);
@Override public boolean equals (Object o) {if (o = =) 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 use 31, this is the recommended value, the study shows that this number is better than the performance of public int hashcode () {int = 17;
result = ~ result + AreaCode;
result = ~ result + prefix;
result = ~ result + linenumber;
return result;
///If an object is not constantly changing, and the overhead is large, consider the hash code cached within the object///volatile modified variable, the thread will read the variable's maximum value after each time the variable is used.
private volatile int hashcode;
@Override public int hashcode () {int. result = Hashcode;
if (result = = 0) {result = 17;
result = ~ result + AreaCode;
result = ~ result + prefix;
result = ~ result + linenumber;
Hashcode = result;
return result; public static void Main (string[] args) {map<phonenumber, string> m = new Hashmap<phonenumber, Strin
G> ();
M.put (New PhoneNumber (707, 867, 5309), "Jenny");
It's not going to go back to Jenny. Oh, it will return NULL, this is because the put object they are placed in a different hash bucket System.out.println (M.get (New PhoneNumber (707, 867, 5309)); }
}
Thank you for reading, I hope to help you, thank you for your support for this site!