KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > displaytag > model > DefaultComparator


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 JavaDoc;
15 import java.util.Comparator JavaDoc;
16
17
18 /**
19  * Default comparator. Was previously part of RowSorter.
20  * @author fguist
21  * @author rapruitt
22  * @version $Revision: 986 $ ($Author: fgiust $)
23  */

24 public class DefaultComparator implements Comparator JavaDoc
25 {
26
27     /**
28      * Use this collator.
29      */

30     private Collator JavaDoc collator;
31
32     /**
33      * Instantiate a default comparator with no collator specified.
34      */

35     public DefaultComparator()
36     {
37         this.collator = Collator.getInstance();
38         collator.setStrength(Collator.PRIMARY); // ignore case and accents
39
}
40
41     /**
42      * Instantiate a default comparator with a specified collator.
43      * @param collatorToUse collator instance
44      */

45     public DefaultComparator(Collator JavaDoc collatorToUse)
46     {
47         this.collator = collatorToUse;
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 JavaDoc object1, Object JavaDoc object2)
58     {
59         int returnValue;
60         if (object1 instanceof String JavaDoc && object2 instanceof String JavaDoc)
61         {
62             returnValue = collator.compare(object1, object2);
63         }
64         else if (object1 instanceof Comparable JavaDoc && object2 instanceof Comparable JavaDoc)
65         {
66             returnValue = ((Comparable JavaDoc) 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 }
76
Popular Tags