1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package de.fu_berlin.ties.util;
23
24 import java.util.Comparator;
25
26 import org.apache.commons.lang.builder.ToStringBuilder;
27
28 /***
29 * Compares objects, inverting the order of a wrapped comparator. This means
30 * that numeric objects will be sorted in decreasing order etc.
31 *
32 * @author Christian Siefkes
33 * @version $Revision: 1.5 $, $Date: 2004/09/07 10:01:37 $, $Author: siefkes $
34 */
35 public class InvertedComparator<T> implements Comparator<T> {
36
37 /***
38 * The comparator wrapped and inverted by this instance.
39 */
40 private final Comparator<T> wrappedComparator;
41
42 /***
43 * Creates a new instance, inverting the order returned by the provided
44 * comparator.
45 * @param wrappedComp the comparator to wrap and invert; must not be
46 * <code>null</code>
47 */
48 public InvertedComparator(final Comparator<T> wrappedComp) {
49 super();
50 wrappedComparator = wrappedComp;
51 }
52
53 /***
54 * Compares its two arguments for order. Inverts the natural ordering
55 * of the two arguments resp. if order of the {@link #getWrappedComparator()
56 * wrapped comparator}, if any. So this method returns a negative integer,
57 * zero, or a positive integer as the first argument is greater than,
58 * equal to, or less than the second.
59 *
60 * @param o1 the first object to be compared
61 * @param o2 the second object to be compared
62 * @return the inverted ordering of the arguments
63 */
64 public int compare(final T o1, final T o2) {
65 return -wrappedComparator.compare(o1, o2);
66 }
67
68 /***
69 * Returns the comparator wrapped and inverted by this instance.
70 *
71 * @return the value of the attribute
72 */
73 public Comparator getWrappedComparator() {
74 return wrappedComparator;
75 }
76
77 /***
78 * Returns a string representation of this object.
79 *
80 * @return a textual representation
81 */
82 public String toString() {
83 return new ToStringBuilder(this)
84 .append("wrapped comparator", wrappedComparator)
85 .toString();
86 }
87
88 }