1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32 package com.generationjava.compare;
33
34 import java.util.Comparator;
35 import java.util.HashMap;
36 import java.util.Map;
37
38 import com.generationjava.collections.ClassMap;
39
40 import org.apache.commons.collections.comparators.ComparableComparator;
41
42 /***
43 * Attempts to compare any Object.
44 * Some standard types of objects can be dealt with immediately,
45 * but others will need a Comparator being added with the static
46 * registerComparator method.
47 *
48 * The following are already handled:
49 *
50 * Any extension of Comparable. This includes all the Number's and
51 * String, Character amongst others.
52 * java.net.URL is handled.
53 */
54 public class ObjectComparator implements Comparator {
55
56 static private Map registry = new ClassMap( new HashMap() );
57
58 static {
59 Comparator cc = new ComparableComparator();
60 registry.put(java.lang.Comparable.class, cc);
61
62
63 registry.put(java.lang.String.class, cc);
64 registry.put(java.lang.Number.class, cc);
65 registry.put(java.io.File.class, cc);
66 registry.put(java.lang.Character.class, cc);
67 registry.put(java.math.BigDecimal.class, cc);
68 registry.put(java.lang.Byte.class, cc);
69 registry.put(java.lang.Long.class, cc);
70 registry.put(java.lang.Short.class, cc);
71 registry.put(java.lang.Float.class, cc);
72 registry.put(java.lang.Double.class, cc);
73 registry.put(java.math.BigInteger.class, cc);
74
75 registry.put(java.net.URL.class, new UrlComparator());
76 }
77
78 /***
79 * Register a Comparator to be used to compare a particular Class.
80 */
81 static public void registerComparator(Class clss, Comparator c) {
82 registry.put(clss, c);
83 }
84
85 /***
86 * Get the Comparator to be used for a particular Class.
87 * If no Comparator is available, then it will search the
88 * inheritence tree for one.
89 */
90 static public Comparator getComparator(Class clss) {
91
92 if(clss == null) {
93 return null;
94 }
95
96 return (Comparator)registry.get(clss);
97 }
98
99 public ObjectComparator() {
100 }
101
102 public int compare(Object o1, Object o2) {
103 if(o1 == null) {
104 return -1;
105 } else
106 if(o2 == null) {
107 return 1;
108 }
109
110 if(o1.getClass() != o2.getClass()) {
111 return -1;
112 }
113
114 Comparator subCom = getComparator(o1.getClass());
115 if(subCom == null) {
116 return -1;
117 } else {
118 return subCom.compare(o1, o2);
119 }
120 }
121
122 }