001package org.unix4j.util.sort;
002
003import java.util.Comparator;
004
005/**
006 * Forwards calls to another {@link Comparator} but reverses the order. The
007 * class provides a static {@link #reverse(Comparator)} method but no public
008 * constructor.
009 */
010public final class ReverseOrderComparator<T> implements Comparator<T> {
011
012        private final Comparator<T> comparator;
013
014        /**
015         * Private constructor used by {@link #reverse(Comparator)}.
016         * 
017         * @param comparator
018         *            the comparator to reverse
019         */
020        private ReverseOrderComparator(Comparator<T> comparator) {
021                this.comparator = comparator;
022        }
023
024        /**
025         * Reverses the given comparator and returns the resulting comparator.
026         * 
027         * @param <T>
028         *            the generic type for the compared values
029         * @param comparator
030         *            the comparator to reverse
031         * @return a comparator sorting elements in reverse order compared to the
032         *         given {@code comparator} argument
033         */
034        public static <T> Comparator<T> reverse(Comparator<T> comparator) {
035                if (comparator instanceof ReverseOrderComparator) {
036                        return ((ReverseOrderComparator<T>) comparator).comparator;
037                }
038                return new ReverseOrderComparator<T>(comparator);
039        }
040
041        @Override
042        public int compare(T o1, T o2) {
043                return comparator.compare(o2, o1);//swap args to reverse order
044        }
045}