KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > icl > saxon > sort > StringComparer


1 package com.icl.saxon.sort;
2
3
4 /**
5  * A Comparer used for comparing keys. This comparer uses the binary Unicode value of the
6  * characters.
7  *
8  * @author Michael H. Kay (mhkay@iclway.co.uk)
9  *
10  */

11
12 public class StringComparer extends TextComparer {
13
14     /**
15     * Compare two string objects using default collating
16     * @return <0 if a<b, 0 if a=b, >0 if a>b
17     * @throws ClassCastException if the objects are of the wrong type for this Comparer
18     */

19
20     public int compare(Object JavaDoc a, Object JavaDoc b) {
21         char[] a1 = ((String JavaDoc)a).toCharArray();
22         char[] b1 = ((String JavaDoc)b).toCharArray();
23         int alen = a1.length;
24         int blen = b1.length;
25         int i = 0;
26         int j = 0;
27         while (true) {
28             if (i==alen && j==blen) return 0;
29             if (i==alen) return -1;
30             if (j==blen) return +1;
31             int diff = a1[i++] - b1[j++];
32             if (diff!=0) return diff;
33         }
34     }
35
36     /**
37     * Set case order
38     * @param caseOrder one of DEFAULT_CASE_ORDER, LOWERCASE_FIRST, or UPPERCASE_FIRST.
39     * Indicates whether upper case letters precede or follow lower case letters in the ordering
40     * @return either this or a different Comparer that will be used to perform the comparisons.
41     * This allows the TextComparer to delegate the comparison to a Comparer dedicated to a
42     * specific case order.
43     */

44
45     public Comparer setCaseOrder(int caseOrder) {
46         if (caseOrder==LOWERCASE_FIRST) {
47             return new LowercaseFirstComparer();
48         }
49         if (caseOrder==UPPERCASE_FIRST) {
50             return new UppercaseFirstComparer();
51         }
52         return this;
53     }
54
55
56 }
57
Popular Tags