下面我把Effective Java的样例代码列出,并用Guava重新了toString方法
// 重写PhoneNumber的toString方法 - Effective Java中文第二版第44页
package org.effectivejava.examples.chapter03.item10;
import java.util.HashMap;
import java.util.Map;
import com.google.common.base.Objects;
public final 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
public int hashCode() {
int result = 17;
result = 31 * result + areaCode;
result = 31 * result + prefix;
result = 31 * result + lineNumber;
return result;
}
//Effective Java原有的toString方法
/*
* @Override public String toString() { return
* String.format("(%03d) %03d-%04d", areaCode, prefix, lineNumber); }
*/
/**
* 采用Guava实现的toString
*
*/
@Override
public String toString() {
return Objects.toStringHelper(this)
.addValue(String.format("(%03d) %03d-%04d", areaCode, prefix,lineNumber))
.add("areaCode", areaCode)
.add("prefix", prefix)
.add("lineNumber", lineNumber)
.toString();
}
public static void main(String[] args) {
Map<PhoneNumber, String> m = new HashMap<PhoneNumber, String>();
m.put(new PhoneNumber(707, 867, 5309), "Jenny");
System.out.println(m);
}
}
输出对比