01: package com.jidesoft.comparator;
02:
03: import java.util.Comparator;
04:
05: /**
06: * Badly named, this class compares objects by first converting them to
07: * <tt>String</tt>s using the <tt>toString</tt> method.
08: */
09: public class DefaultComparator implements Comparator {
10: private static DefaultComparator singleton = null;
11:
12: /**
13: * Constructor.
14: * <p/>
15: * Has protected access to prevent other clients creating instances of the
16: * class ... it is stateless so we need only one instance.
17: */
18: protected DefaultComparator() {
19: }
20:
21: /**
22: * Returns <tt>ObjectComparator</tt> singleton.
23: *
24: * @return an instance of DefaultComparator.
25: */
26: public static DefaultComparator getInstance() {
27: if (singleton == null)
28: singleton = new DefaultComparator();
29: return singleton;
30: }
31:
32: /**
33: * Compares two Objects <b>using the <tt>toString()</tt> method</b> as the
34: * value of each object to compare.
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 <lt> b, 1 if a <gt> 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: final String s1 = o1.toString();
50: final String s2 = o2.toString();
51: return s1.compareTo(s2);
52: }
53: }
|