(x.compareTo(y)==0) == (x.equals(y))

来源:互联网 发布:好的代理软件 编辑:程序博客网 时间:2024/06/08 16:13

对象实现 Comparable 接口, 重写 CompareTo() 方法,则 findbug 提示需要重写 equals() 方法,进而提示需要重写 hashCode() 方法。

Class defines compareTo(…) and uses 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.”

简要翻译

Java Bean类实现了 Comparable 接口,但却使用了父类( java.lang.Object 类)的 equals 方法 (没有覆盖父类的实现,违反了接口的使用规则)
(x.compareTo(y)==0) == (x.equals(y))
compareTo return 0时,只有当equals方法return true;
如违反了这一规则,在一些类中会发生一些奇怪的、不可预知的错误,如优先队列PriorityQueue, 使用PriorityQueue.remove 方法时,JDK5使用的是对象的compareTo方法,JDK1.6中使用了equals方法,所以为了保持一致,应该使 (x.compareTo(y)==0) == (x.equals(y)).

强烈推荐 (x.compareTo(y)==0) == (x.equals(y)) 这种做法,但不是 严格要求这样做。一般来说,任何实现 Comparable 接口而且违背此条件的类都应该清楚地指出这一事实。推荐如此阐述:“注意:此类具有与 equals 不一致的自然排序。”

所以需要重写 equals() 方法


Class defines equals() and uses Object.hashCode()

This class overrides equals(Object), but does not override hashCode(), and inherits the implementation of hashCode() from java.lang.Object (which returns the identity hash code, an arbitrary value assigned to the object by the VM). Therefore, the class is very likely to violate the invariant that equal objects must have equal hashcodes.

If you don’t think instances of this class will ever be inserted into a HashMap/HashTable, the recommended hashCode implementation to use is:

public int hashCode() {  assert false : "hashCode not designed";  return 42; // any arbitrary constant will do}

简要翻译

Java Bean类实现了 equals()方法,但却使用了父类( java.lang.Object 类)的 hashCode() 方法,未覆盖 java.lang.Object 类的 hashCode() 方法,并继承了父类( java.lang.Object 类)的 hashCode() 方法的实现,因此,此类很有可能违反“相同对象具有相同hash值的”不变性。

如果你认为这个类的实例不会被插入一个HashMap和Hashtable,推荐使用hashCode的实现:

public int hashCode() {  assert false : "hashCode not designed";  return 42; // any arbitrary constant will do}

所以需要重写 hashCode() 方法

2 0
原创粉丝点击