01: package com.jamonapi.utils;
02:
03: import java.util.Comparator;
04:
05: public class JAMonComparator implements Comparator {
06: private static final int LESSTHAN = -1;
07: private static final int EQUALTO = 0;
08: private static final int GREATERTHAN = 1;
09: private boolean naturalOrder = true;
10: private Comparator childComparator = null;// used if JAMonComparator is used as a decorator.
11:
12: public JAMonComparator() {
13: }
14:
15: public JAMonComparator(boolean naturalOrder) {
16: this .naturalOrder = naturalOrder;
17: ;
18:
19: }
20:
21: public JAMonComparator(boolean naturalOrder,
22: Comparator childComparator) {
23: this .naturalOrder = naturalOrder;
24: this .childComparator = childComparator;
25:
26: }
27:
28: /*
29: * Returns
30: * this object is less than - returns a negative integer,
31: * this object equal to - retunrs zero
32: * this object greater than - return positive integer
33: */
34: public int compare(Object newObj, Object existingObj) {
35: // Note the following if condition ensures that nulls may be in the array.
36: if ((existingObj == null && newObj == null)
37: || !(existingObj instanceof Comparable)
38: || !(newObj instanceof Comparable)) // 2 nulls are considered equal. if either object is not comparable return that they are equal
39: return EQUALTO;
40: // if either other value is null then we don't want this to return less
41: // (i.e. true for this conditional) so return 1 (greater than)
42: // When existing is null always replace.
43: else if (existingObj == null)
44: return GREATERTHAN;
45: else if (newObj == null) // when new is null never replace
46: return LESSTHAN;
47:
48: if (childComparator == null) {
49: // Note I am using the passed in value as the Comparable type as this seems more flexible. For example
50: // You may not have control over the array values, but you do over what comparable value you pass in, but being
51: // as the comparison is really asking if the col value is greater than the comparison value I am taking the negative
52: // value. i.e. The compareTo() test is really asking if the compValue is greater than the colValue so flipping it with a
53: // negative gives us the right answer.
54: return reverseIfNeeded(compareThis(newObj, existingObj));
55: } else
56: return reverseIfNeeded(childComparator.compare(newObj,
57: existingObj));
58:
59: }
60:
61: protected int compareThis(Object newObj, Object existingObj) {
62: Comparable comparable = (Comparable) newObj;
63: return comparable.compareTo(existingObj);
64: }
65:
66: private int reverseIfNeeded(int retVal) {
67: return (naturalOrder) ? retVal : -retVal;
68: }
69:
70: public boolean isNaturalOrder() {
71: return naturalOrder;
72: }
73:
74: }
|