[hyddd的FindBugs分析记录][M B Eq] Class defines compareTo(...) and uses Object.equals()
2009-04-01 20:17 hyddd 阅读(3429) 评论(0) 编辑 收藏 举报[M B Eq] Class defines compareTo(...) and uses Object.equals() [EQ_COMPARETO_USE_OBJECT_EQUALS]
This class defines a compareTo(...)
method but inherits its
equals()
method from java.lang.Object
. Generally, the
value of compareTo should return zero if and only if equals returns true. If
this is violated, weird and unpredictable failures will occur in classes such as
PriorityQueue. In Java 5 the PriorityQueue.remove method uses the compareTo
method, while in Java 6 it uses the equals method.
From the JavaDoc for the compareTo method in the Comparable interface:
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."
重写compareTo有一定的风险,因为你不知道JDK内部做对象对比时,到底使用了compareTo还是equals。例如:在JAVA5 里,PriorityQueue.remove中使用了compareTo,但JAVA6中,PriorityQueue.remove使用了equals方法。
这里Findbugs强烈建议:(x.compareTo(y)==0) == (x.equals(y)),当你重写compareTo的时候,请记得这一点:>,当然这个只是建议,不是绝对的。
作者:hyddd
出处:http://www.cnblogs.com/hyddd/
本文版权归作者所有,欢迎转载,演绎或用于商业目的,但是必须说明本文出处(包含链接)。