0

I have a class TimeParameter that is a not actually a subclass of Date, but composed of a Date amongst other things. In my context, Dates or quite frequently represented as Doubles (Julian dates). Very frequently, a TimeParameter is compared not to a TimeParameter, but to a Date, a Double, or even a String (A Date coded with a predefined format). Originally, TimeParameter implemented the Comparable interface, and in compareTo(Object o), o was used to fork further

if ( o instanceof Date)
    return compareToDate((Date)o);
else if ( o instanceof Double)
    return compareToDouble((Double)o);
else ...

One possibility to do that with generics would involve using a helper class like

CompareHelper(Double d) {
    jd = d;
    ...
}
CompareHelper(Date d) {
    jd = getJulianDate(d);
    ...
}

then, make TimeParameter implement Comparable<CompareHelper> and proceed likewise.

But my question would be, whether there is a way to do that in generics without a helper class as the calling instance is not always capable of knowing that it should wrap the Date/Double into a helper instance.

Thanks in advance

2
  • Am I correct that no matter how the time is stored in the TimeParameter it should be comparable to any other type of time specification (Date, Double, String)? If so, I think your first (non-generic) implementation was the best. Commented Apr 17, 2012 at 12:27
  • A few things: first, your CompareHelper isn't a generic class - rather, it's another time class that converts from other time classes to a standard time class (jd), and I'm not sure that generics are the right solution. Second, as solutions go, the instanceof solution isn't bad (perhaps inelegant, but not bad). Third, when you have multiple ways of representing the same information (time/dates) used across your code, that suggests (to me) something smelly going on - in that respect, I might suggest you take a look at more recent attempts to handle dates/time in Java: e.g. jodaTime or jsr310 Commented Apr 17, 2012 at 12:35

1 Answer 1

2

Normally all the types would have a common interface they all implement. It doesn't make sense to be comparable to lots of things which have nothing in common.

BTW: a.compareTo(b) == -b.compareTo(a) means you can't get too complicated with the types which you caompare to.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.