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
33
34
35
36
37
38 package com.gargoylesoftware.base.collections;
39
40 import java.text.Collator;
41 import java.util.Comparator;
42 import java.util.Locale;
43
44 /***
45 * A concrete implementation of Comparator that compares two strings. If a locale
46 * is specified then the comparison will be performed using the locale specific
47 * collating sequences. If the locale is not specified then a binary comparison
48 * will be performed.
49 *
50 * @version $Revision: 1.4 $
51 * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
52 */
53 public class StringComparator
54 implements
55 Comparator {
56
57 private final Locale locale_;
58 private final Collator collator_;
59 private final boolean isAscending_;
60
61 /***
62 * Create a locale specific comparator.
63 *
64 * @param locale The locale to be used when determining sorting order.
65 * If locale is null then a binary comparison is performed.
66 * @param collatorStrength The strength value to be used by the
67 * Collator. If locale is null then this value is ignored.
68 * @param isAscending True if we are sorting in ascending order, false
69 * otherwise.
70 */
71 public StringComparator(
72 final Locale locale,
73 final int collatorStrength,
74 final boolean isAscending ) {
75
76 locale_ = locale;
77 if( locale_ == null ) {
78 collator_ = null;
79 }
80 else {
81 collator_ = Collator.getInstance(locale_);
82 collator_.setStrength( collatorStrength );
83 }
84 isAscending_ = isAscending;
85 }
86
87 /***
88 * Create a locale specific comparator.
89 *
90 * @param locale The locale to be used when determining sorting order.
91 * If locale is null then a binary comparison is performed.
92 */
93 public StringComparator( final Locale locale ) {
94 this( locale, Collator.PRIMARY, true );
95 }
96
97 /***
98 * Compare the two strings.
99 * @param object1 The first string.
100 * @param object2 The second string.
101 * @return a negative integer, zero, or a positive integer as the first
102 * argument is less than, equal to, or greater than the second.
103 */
104 public int compare( final Object object1, final Object object2 ) {
105 int rc;
106
107 final String string1 = object1.toString();
108 final String string2 = object2.toString();
109
110 if( locale_ == null ) {
111
112
113 rc = string1.compareTo(string2);
114 }
115 else {
116
117 rc = collator_.compare( string1, string2 );
118 }
119
120
121 if( isAscending_ == false ) {
122 rc *= -1;
123 }
124
125 return rc;
126 }
127 }
128