calendar.equals is evil (especially over RMI)

And again I stumbled across a problem of the date/time API of the JVM.

This time it is the java.util.Calendar object. The Calendar object violates against the

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

It’s not a rule, but as it says in the contract “It is strongly recommended, but not strictly required”.

So what does calendar.equals against calendar.compareTo?

calendar.compareTo only compares the milliseconds since 1.1.1970 GMT+0:00, which as we all know is the time measurement of Java.

calendar.equals does that too, but it also takes other more location related things into it’s comparison. It also uses isLenient, getFirstDayOfWeek, getMinimalDaysInFirstWeek and getTimeZone for comparism.
Lenient is usually true. The timezone is something you might really want to consider in a comparison (especially in JUnit Tests). The other two attributes
getFirstDayOfWeek and getMinimalDaysInFirstWeek are locale dependend.

If you are comparing the Calendars on the same system, they should be equals all the time, as long as you don’t change the timezone. But if you got an Calendar object over RMI, it can contain other values, because it is from an other system, where another locale is defined.

The library Joda-Time has the inconsistence, between equals and compareTo, too. But they have an isEquals method especially for that. But the equals method of Joda-Time does only compare the time in millis, the timezone and the Chronology (calendar system), not something stupid as what is the first day of the week.

This entry was posted in Java, Problems and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *