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 //至於為什麼使用31,這個是推薦值,研究表明這個數字用起來性能比較好 public int hashCode() { int result = 17; result = 31 * result + areaCode; result = 31 * result + prefix; result = 31 * result + lineNumber; return result; } */ //如果一個對象不是經常變動,而且開銷比較大的話,就要考慮吧散列碼緩存在對象內部 //用volatile修飾的變量,線程在每次使用變量的時候,都會讀取變量修改後的最的值。 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哦,會返回null,這個是因為put對象吧他們放到不同的散列桶中 System.out.println(m.get(new PhoneNumber(707, 867, 5309))); } }