0

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?

ben3000
  • 4,629
  • 6
  • 24
  • 43
  • 1
    Because it doesn't `implements Comparable`? What's your question here? – CollinD Mar 31 '16 at 02:53
  • 1
    write your own wrapper that implements Comparable – Scary Wombat Mar 31 '16 at 02:55
  • Yeah, that's the technical reason, but I'm more after "why not", given many of the other classes are comparable. – ben3000 Mar 31 '16 at 02:56
  • No one can answer that except the developers of Joda. – CollinD Mar 31 '16 at 02:57
  • In regard to the downvotes, I quote @PaulSonier (see [this question from 6 years ago](http://stackoverflow.com/questions/889160/what-is-a-wrapper-class)): "I don't see the harm of having a set of basic questions in the SO archives. SO is for beginners as well as for experts; just because you find something 'stupid' doesn't mean that everyone does." – ben3000 Apr 01 '16 at 02:08

1 Answers1

4

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.

Community
  • 1
  • 1