Guava Objects是个非常好用的类,帮助我们写出hashCode(), equals()和toString()。
看下面的小例子。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
public class TryObjects { private int i; private Double d; /** * Default ctor. */ public TryObjects() { this(10, 1.0); } /** * Ctor with i and d. * @param i i * @param d d */ public TryObjects(int i, double d) { this(i, d); } @Override public boolean equals(Object arg0) { if (arg0 == null || !(arg0 instanceof TryObjects)) { return false; } else { TryObjects obj = (TryObjects)arg0; return Objects.equal(this.i, obj.i) && Objects.equal(this.d, obj.d); // 不用担心null的情况 } } @Override public int hashCode() { return Objects.hashCode(this.i, this.d); } @Override public String toString() { // TryObjects{i=10, d=1.0} return Objects.toStringHelper(TryObjects.class) .add("i", this.i) .add("d", this.d) .toString(); } } |