文章40页有错误,m.get(new PhoneNumber(408,867,5309))应该改为m.get(new PhoneNumber(707,867,5309)),与文章上面的HashMap例子一致,对于文章中的代码,我自己手敲整理了下。
首先是PhoneNumber类,如下代码
public classPhoneNumber {
private shortareaCode;
private shortprefix;
private shortlineNumber;
publicPhoneNumber(intareaCode, intprefix, intlineNumber){
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 voidrangeCheck(intarg, intmax,String name){
if(arg <0|| arg > max){
throw newIllegalArgumentException(name +":"+ arg);
}
}
@Override
public booleanequals(Object o) {
if(o ==this){
return true;
}
if(!(oinstanceofPhoneNumber)){
return false;
}
PhoneNumber pn = (PhoneNumber)o;
returnpn.lineNumber==lineNumber&& pn.prefix==prefix&& pn.areaCode==areaCode;
}
private volatile inthashCode;// 轻量级线程安全
@Override
public inthashCode() {
intresult =hashCode;
if(result ==0){
result =17;// 可以任意不等于0的值
intprimeNumber =31;// 奇素数
result = primeNumber * result +areaCode;
result = primeNumber * result +prefix;
result = primeNumber * result +lineNumber;
hashCode= result;
}
returnresult;
}
@Override
publicStringtoString() {
returnString.format("(%03d) %03d-%04d",areaCode,prefix,lineNumber);
}
}
调用如上代码,如下
Map<PhoneNumber,String> m =newHashMap<PhoneNumber,String>();
m.put(newPhoneNumber(707,867,5309),"Jenny");// 存储到map中
m.get(newPhoneNumber(707,867,5309));// 从map中取出