1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 package org.apache.commons.codec;
19
20 import java.util.Comparator;
21
22 /**
23 * Strings are comparable, and this comparator allows
24 * you to configure it with an instance of a class
25 * which implements StringEncoder. This comparator
26 * is used to sort Strings by an encoding scheme such
27 * as Soundex, Metaphone, etc. This class can come in
28 * handy if one need to sort Strings by an encoded
29 * form of a name such as Soundex.
30 *
31 * @author Apache Software Foundation
32 * @version $Id: StringEncoderComparator.java 582444 2007-10-06 04:10:48Z bayard $
33 */
34 public class StringEncoderComparator implements Comparator {
35
36 /**
37 * Internal encoder instance.
38 */
39 private final StringEncoder stringEncoder;
40
41 /**
42 * Constructs a new instance.
43 * @deprecated as creating without a StringEncoder will lead to a
44 * broken NullPointerException creating comparator.
45 */
46 public StringEncoderComparator() {
47 stringEncoder = null; // Trying to use this will cause things to break
48 }
49
50 /**
51 * Constructs a new instance with the given algorithm.
52 * @param stringEncoder the StringEncoder used for comparisons.
53 */
54 public StringEncoderComparator(StringEncoder stringEncoder) {
55 this.stringEncoder = stringEncoder;
56 }
57
58 /**
59 * Compares two strings based not on the strings
60 * themselves, but on an encoding of the two
61 * strings using the StringEncoder this Comparator
62 * was created with.
63 *
64 * If an {@link EncoderException} is encountered, return <code>0</code>.
65 *
66 * @param o1 the object to compare
67 * @param o2 the object to compare to
68 * @return the Comparable.compareTo() return code or 0 if an encoding error was caught.
69 * @see Comparable
70 */
71 public int compare(Object o1, Object o2) {
72
73 int compareCode = 0;
74
75 try {
76 Comparable s1 = (Comparable) this.stringEncoder.encode(o1);
77 Comparable s2 = (Comparable) this.stringEncoder.encode(o2);
78 compareCode = s1.compareTo(s2);
79 }
80 catch (EncoderException ee) {
81 compareCode = 0;
82 }
83 return compareCode;
84 }
85
86 }