Does a natural comparator exist in the standard api?

I need a comparator as part of a strategy pattern that can either use the natural ordering of the objects or some custom ordering. For the natural ordering case, I wrote a simple comparator:

private static class NaturalComparator<T extends Comparable<? super T>> implements Comparator<T> {
    @Override
    public int compare(T o1, T o2) {
        return o1.compareTo(o2);
    }
}

Seems simple enough, but I was wondering if anyone knew of one in the standard API. I looked at TreeMap, and it does it without such a class, so when that code was written, the apparent answer would be no, but perhaps it was added later.


Added to Comparator in Java 8:

static <T extends Comparable<? super T>> Comparator<T> naturalOrder()

Use it like this, for example:

Comparator<Double> natural = Comparator.<Double>naturalOrder();
return natural.compare(1.0, 1.1));

Yes, the JDK definitely has it! Here it is:

Collections.reverseOrder(Collections.reverseOrder())

Just kidding. (But it's true. (Just don't actually use that. (Ever.)))


JDK没有它,但它被称为ComparableComparator ,它存在于很多框架中,比如Spring,Apache Commons,Hibernate和其他许多框架

链接地址: http://www.djcxy.com/p/91930.html

上一篇: 不同类型的可比较物

下一篇: 标准api中是否存在自然比较器?