我經常有Comparator
類型,而我需要Comparable
,反之亦然。是否有可重複使用的JDK API相互轉換?沿着線的東西:將Comparable從Comparable轉換爲Comparable?
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);
}
};
}
對於仿製藥友好的實現,番石榴的['Ordering.natural()'](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/ common/collect/Ordering.html#natural())的作品,並且有很多額外的功能。 –