1 /**
2 * Licensed under the Artistic License; you may not use this file
3 * except in compliance with the License.
4 * You may obtain a copy of the License at
5 *
6 * http://displaytag.sourceforge.net/license.html
7 *
8 * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
9 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
10 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
11 */
12 package org.displaytag.model;
13
14 import java.text.Collator;
15 import java.util.Comparator;
16
17
18 /**
19 * Default comparator. Was previously part of RowSorter.
20 * @author fguist
21 * @author rapruitt
22 * @version $Revision: 1085 $ ($Author: rapruitt $)
23 */
24 public class DefaultComparator implements Comparator
25 {
26
27 /**
28 * Use this collator.
29 */
30 private Collator collator;
31
32 /**
33 * Instantiate a default comparator with no collator specified.
34 */
35 public DefaultComparator()
36 {
37 this(Collator.getInstance());
38 }
39
40 /**
41 * Instantiate a default comparator with a specified collator.
42 * @param collatorToUse collator instance
43 */
44 public DefaultComparator(Collator collatorToUse)
45 {
46 this.collator = collatorToUse;
47 collator.setStrength(Collator.PRIMARY); // ignore case and accents
48 }
49
50 /**
51 * Compares two given objects. Not comparable objects are compared using their string representation. String
52 * comparisons are done using a Collator.
53 * @param object1 first parameter
54 * @param object2 second parameter
55 * @return the value
56 */
57 public int compare(Object object1, Object object2)
58 {
59 int returnValue;
60 if (object1 instanceof String && object2 instanceof String)
61 {
62 returnValue = collator.compare(object1, object2);
63 }
64 else if (object1 instanceof Comparable && object2 instanceof Comparable)
65 {
66 returnValue = ((Comparable) object1).compareTo(object2);
67 }
68 else
69 {
70 // if object are not null and don't implement comparable, compare using string values
71 returnValue = collator.compare(object1.toString(), object2.toString());
72 }
73 return returnValue;
74 }
75 }