简体   繁体   中英

Java: Comparable implementation with Generics if comparable to two or more type of Objects

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM