01: package com.jidesoft.comparator;
02:
03: import java.util.Calendar;
04: import java.util.Comparator;
05:
06: /**
07: * Comparator for Calendar type. This is a singleton class. Call getInstance() to
08: * get the comparator.
09: */
10: public class CalendarComparator implements Comparator {
11: private static CalendarComparator singleton = null;
12:
13: /**
14: * Constructor.
15: * <p/>
16: * Has protected access to prevent other clients creating instances of the
17: * class ... it is stateless so we need only one instance.
18: */
19: protected CalendarComparator() {
20: }
21:
22: /**
23: * Returns <tt>CalendarComparator</tt> singleton.
24: *
25: * @return an instance of CalendarComparator.
26: */
27: public static CalendarComparator getInstance() {
28: if (singleton == null)
29: singleton = new CalendarComparator();
30: return singleton;
31: }
32:
33: /**
34: * Compares two <tt>Calendar</tt>s.
35: *
36: * @param o1 the first object to be compared
37: * @param o2 the second object to be compared
38: * @return 0 if a and b are equal, -1 if a is before b, 1 if a is after b.
39: */
40: public int compare(Object o1, Object o2) {
41: if (o1 == null && o2 == null) {
42: return 0;
43: } else if (o1 == null) {
44: return -1;
45: } else if (o2 == null) {
46: return 1;
47: }
48:
49: if (o1 instanceof Calendar) {
50: if (o2 instanceof Calendar) {
51: Calendar l = (Calendar) o1;
52: Calendar r = (Calendar) o2;
53:
54: if (l.before(r))
55: return -1;
56: else if (l.equals(r))
57: return 0;
58: else
59: return 1;
60: } else {
61: // o2 wasn't comparable
62: throw new ClassCastException(
63: "The first argument of this method was not a Calendar but "
64: + o2.getClass().getName());
65: }
66: } else if (o2 instanceof Calendar) {
67: // o1 wasn't comparable
68: throw new ClassCastException(
69: "The second argument of this method was not a Calendar but "
70: + o1.getClass().getName());
71: } else {
72: // neither were comparable
73: throw new ClassCastException(
74: "Both arguments of this method were not Calendars. They are "
75: + o1.getClass().getName() + " and "
76: + o2.getClass().getName());
77: }
78: }
79: }
|