java.lang.Comparable and equals

懵懂的女人 提交于 2019-11-28 08:59:09

While it is recommended (and pretty sensible) that having a.compareTo(b) == 0 imply that a.equals(b) (and visa versa), it is not required. Comparable is intended to be used when performing an ordering on a series of objects, whereas equals() just tests for straight equality.

This link has some good information on implementing compareTo properly.

From Javadoc of java.lang.Comparable:

It is strongly recommended (though not required) that natural orderings be consistent with equals.

While it is recommended, it is not required that .equals() and .compareTo() have the same behaviour.

Just look at the BigDecimal API: http://download.oracle.com/javase/1,5.0/docs/api/java/math/BigDecimal.html#equals(java.lang.Object)

Let's say the way I term two objects as equal within the equals() method is different from the way I term two objects of the same class as equal within the toCompare() of the Comparable?

If you do this, and you put those objects into a sorted set, the set will misbehave. From the docs on SortedSet:

Note that the ordering maintained by a sorted set (whether or not an explicit comparator is provided) must be consistent with equals if the sorted set is to correctly implement the Set interface.

For example, a TreeSet may (erroneously) contain two objects where

a.compareTo(b) != 0

even though

a.equals(b) == true
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!