样本等于方法:
@Override public boolean equals(Object obj) { if (obj != null && obj instanceof MyClass) { MyClass msg = (MyClass)obj; return this.compareTo(msg) == 0; } return false; }
编辑:
从Comparable的文档引用
The natural ordering for a class C is said to be consistent with
equals if and only if e1.compareTo(e2) == 0 has the same boolean value
as e1.equals(e2) for every e1 and e2 of class C. Note that null is not
an instance of any class,and e.compareTo(null) should throw a
NullPointerException even though e.equals(null) returns false
编辑:
经过进一步审查,我发现注意到,Comparable文件还说明如下:
The implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y. (This implies that x.compareTo(y) must throw an exception iff y.compareTo(x) throws an exception.)
Ergo,因为null.compareTo(x)显然会抛出一个NPE,x.compareTo(null)也应该抛出一个NPE.而对于平等而言,情况并非如此.对于NPE的正确处理我很大,所以我觉得这个比较重要.
解决方法
根据JavaDoc:
Note that null is not an instance of any class,and e.compareTo(null)
should throw a NullPointerException even though e.equals(null) returns
false.It is strongly recommended,but not strictly required that
(x.compareTo(y)==0) == (x.equals(y)). Generally speaking,any class
that implements the Comparable interface and violates this condition
should clearly indicate this fact. The recommended language is “Note:
this class has a natural ordering that is inconsistent with equals.”
您可以随意在equals()方法中重用compareTo()方法逻辑,但请记住所有与equals(),hashCode()的合约以及来自JavaDoc for compareTo()方法的合同.如果他们不相互冲突,那么继续.
我认为执行合同更重要.