Are there any standard Java classes with inconsistent compareTo() and equals()?

There actually seems to be a few examples, but some are not well documented in the code or JavaDoc. This blog post by Stephen Colebourne gives the details, but in summary the following classes are inconsistent with equals:

  • java.math.BigDecimal
  • java.io.ObjectStreamField
  • javax.management.ObjectName (have not been able to reproduce an example though)
  • java.util.Calendar
  • java.util.GregorianCalendar

For example:

ObjectStreamField a = new ObjectStreamField("foo", String.class);
ObjectStreamField b = new ObjectStreamField("foo", String.class);
a.equals(b); // false, checks object equality
a.compareTo(b); // 0

As noted by Olivier, Java 8 also adds java.time.zone.ZoneOffsetTransition

Notably java.time.OffsetTime has avoided inconsistency by adding extra methods isAfter, isBefore and isEqual for doing time-line comparison/equality-checking.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)