ben3000
ben3000

Reputation: 5029

Why wasn't Joda Interval made comparable?

I've been attempting to generate a TreeMap<Interval, Set<Object>> for storing person entities in age-grouped sets where the Interval describes the boundary of the age group. I got the following error when I attempted to do this.

java.lang.ClassCastException: org.joda.time.Interval cannot be cast to java.lang.Comparable

Swapping Interval for a DateTime works perfectly, but the map's key then must be used as input to create an Interval.

Why wasn't Joda Interval made comparable?

Upvotes: 0

Views: 334

Answers (1)

Pierre-Luc Bertrand
Pierre-Luc Bertrand

Reputation: 740

Intervals can be compared in many ways. The javadoc of Interval states it explicitly:

The duration is represented separately by ReadableDuration. As a result, intervals are not comparable. To compare the length of two intervals, you should compare their durations.

An interval can also be converted to a ReadablePeriod.

For a longer explanation, consider the following intervals and define how they should be ordered:

10:00 - 12:00
11:00 - 13:00
11:00 - 12:00
 9:00 - 10:00
 9:00 - 13:00

Should they be ordered by duration (timespan)?

11:00 - 12:00  (1 hours)
 9:00 - 10:00  (1 hours)
10:00 - 12:00  (2 hours)
11:00 - 13:00  (2 hours)
 9:00 - 13:00  (4 hours)

Or by start time?

 9:00 - 10:00
 9:00 - 13:00
10:00 - 12:00
11:00 - 13:00
11:00 - 12:00

Or by start time, then duration?

 9:00 - 10:00  (1 hours)
 9:00 - 13:00  (4 hours)
10:00 - 12:00  (2 hours)
11:00 - 12:00  (1 hours)
11:00 - 13:00  (2 hours)

Or by end time, then duration?

 9:00 - 10:00  (1 hours)
11:00 - 12:00  (1 hours)
10:00 - 12:00  (2 hours)
11:00 - 13:00  (2 hours)
 9:00 - 13:00  (4 hours)

As you can see, there is no single clear definition of "natural ordering", which is what Comparable defines:

This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.

Upvotes: 4

Related Questions