01: package prefuse.util.collections;
02:
03: /**
04: * Default LiteralComparator implementation that uses the natural ordering
05: * of all data types for comparing values. Object values will need to
06: * implement the {@link java.lang.Comparable} interface.
07: *
08: * @author <a href="http://jheer.org">jeffrey heer</a>
09: */
10: public class DefaultLiteralComparator implements LiteralComparator {
11:
12: // maintain a singleton instance of this class
13: private static DefaultLiteralComparator s_instance = null;
14:
15: /**
16: * Returns an instance of this comparator.
17: * @return a DefaultLiteralComparator
18: */
19: public static DefaultLiteralComparator getInstance() {
20: if (s_instance == null)
21: s_instance = new DefaultLiteralComparator();
22: return s_instance;
23: }
24:
25: /**
26: * @see prefuse.util.collections.LiteralComparator#compare(byte, byte)
27: */
28: public int compare(byte x1, byte x2) {
29: return (x1 < x2 ? -1 : x1 > x2 ? 1 : 0);
30: }
31:
32: /**
33: * @see prefuse.util.collections.LiteralComparator#compare(int, int)
34: */
35: public int compare(int x1, int x2) {
36: return (x1 < x2 ? -1 : x1 > x2 ? 1 : 0);
37: }
38:
39: /**
40: * @see prefuse.util.collections.LiteralComparator#compare(long, long)
41: */
42: public int compare(long x1, long x2) {
43: return (x1 < x2 ? -1 : x1 > x2 ? 1 : 0);
44: }
45:
46: /**
47: * @see prefuse.util.collections.LiteralComparator#compare(float, float)
48: */
49: public int compare(float x1, float x2) {
50: return Float.compare(x1, x2);
51: }
52:
53: /**
54: * @see prefuse.util.collections.LiteralComparator#compare(double, double)
55: */
56: public int compare(double x1, double x2) {
57: return Double.compare(x1, x2);
58: }
59:
60: /**
61: * @see prefuse.util.collections.LiteralComparator#compare(boolean, boolean)
62: */
63: public int compare(boolean x1, boolean x2) {
64: return (x1 ? (x2 ? 0 : 1) : (x2 ? -1 : 0));
65: }
66:
67: /**
68: * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
69: */
70: public int compare(Object o1, Object o2) {
71: if (o1 == null) {
72: return (o2 == null ? 0 : -1);
73: } else if (o2 == null) {
74: return 1;
75: }
76:
77: if (o1 instanceof Comparable) {
78: return ((Comparable) o1).compareTo(o2);
79: } else if (o2 instanceof Comparable) {
80: return -1 * ((Comparable) o2).compareTo(o1);
81: } else if (o1 instanceof Boolean && o2 instanceof Boolean) {
82: // unfortunate hack necessary for Java 1.4 compatibility
83: return compare(((Boolean) o1).booleanValue(),
84: ((Boolean) o2).booleanValue());
85: } else {
86: throw new IllegalArgumentException(
87: "Incomparable arguments.");
88: }
89: }
90:
91: } // end of class DefaultLiteralComparator
|