I often have a Comparator type while I need a Comparable and the other way around. Is there a reusable JDK API to convert from one another? Something along the lines of:
public static <C> Comparable<C> toComparable(final Comparator<C> comparator) {
// does not compile because Hidden can not extend C,
// but just to illustrate the idea
final class Hidden extends C implements Comparable<C> {
@Override
public int compareTo(C another) {
return comparator.compare((C) this, another);
}
};
return new Hidden();
}
public static <C extends Comparable<C>> Comparator<C> toComparator(final Class<C> comparableClass) {
return new Comparator<C>() {
@Override
public int compare(C first, C second) {
assert comparableClass.equals(first.getClass());
assert comparableClass.equals(second.getClass());
return first.compareTo(second);
}
};
}
ComparableComparatorfrom Apache Commons Collections seems to addressComparable<T>toComparatorproblem (unfortunately its not generic type-friendly).The reverse operation is not quite possible because the
Comparator<T>represents algorithm whileComparable<T>represents actual data. You will need composition of some sort. Quick and dirty solution:Say you have class
Foothat is notComparable<Foo>but you haveComparator<Foo>. You use it like this:As you can see (especially without mixins) it’s pretty ugly (and I’m not even sure if it’ll work…) Also notice that
comparabledoesn’t extendFoo, you have to call.getInstance()instead.