01: /*
02: * @(#)FastComparableComparator.java 2/27/2007
03: *
04: * Copyright 2002 - 2007 JIDE Software Inc. All rights reserved.
05: */
06:
07: package com.jidesoft.comparator;
08:
09: import java.io.Serializable;
10: import java.util.Comparator;
11:
12: /**
13: * A Comparator that compares Comparable objects.
14: * Throws ClassCastExceptions if the objects are not
15: * Comparable, or if they are null.
16: * Different from {@link ComparableComparator}, it will not throw exception
17: * when the two compareTo methods don't provide an inverse result of each other
18: * as per the Comparable javadoc. We do so mainly to reduce one call to compareTo.
19: * <br>
20: * If both objects are null, they will be treated as equal. If one is null and the other
21: * is not, the null value will be treated as smaller then non-null value.
22: *
23: * @author bayard@generationjava.com
24: * @author JIDE Software
25: */
26: public class FastComparableComparator implements Comparator,
27: Serializable {
28:
29: private static final FastComparableComparator instance = new FastComparableComparator();
30:
31: /**
32: * Return a shared instance of a ComparableComparator. Developers are
33: * encouraged to use the comparator returned from this method instead of
34: * constructing a new instance to reduce allocation and GC overhead when
35: * multiple comparable comparators may be used in the same VM.
36: *
37: * @return an instance of ComparableComparator.
38: */
39: public static FastComparableComparator getInstance() {
40: return instance;
41: }
42:
43: /**
44: * Constructs a ComparableComparator.
45: */
46: public FastComparableComparator() {
47: }
48:
49: public int compare(Object o1, Object o2) {
50: if (o1 == null && o2 == null) {
51: return 0;
52: } else if (o1 == null) {
53: return -1;
54: } else if (o2 == null) {
55: return 1;
56: }
57:
58: if (o1 instanceof Comparable) {
59: if (o2 instanceof Comparable) {
60: return ((Comparable) o1).compareTo(o2);
61: } else {
62: // o2 wasn't comparable
63: throw new ClassCastException(
64: "The second argument of this method was not a Comparable: "
65: + o2.getClass().getName());
66: }
67: } else if (o2 instanceof Comparable) {
68: // o1 wasn't comparable
69: throw new ClassCastException(
70: "The first argument of this method was not a Comparable: "
71: + o1.getClass().getName());
72: } else {
73: // neither were comparable
74: throw new ClassCastException(
75: "Both arguments of this method were not Comparables: "
76: + o1.getClass().getName() + " and "
77: + o2.getClass().getName());
78: }
79: }
80: }
|