001 /* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 018 package org.apache.commons.codec; 019 020 import java.util.Comparator; 021 022 /** 023 * Compares Strings using a {@link StringEncoder}. This comparator is used to sort Strings by an encoding scheme such as 024 * Soundex, Metaphone, etc. This class can come in handy if one need to sort Strings by an encoded form of a name such 025 * as Soundex. 026 * 027 * <p>This class is immutable and thread-safe.</p> 028 * 029 * @version $Id: StringEncoderComparator.html 889935 2013-12-11 05:05:13Z ggregory $ 030 */ 031 public class StringEncoderComparator implements Comparator { 032 033 /** 034 * Internal encoder instance. 035 */ 036 private final StringEncoder stringEncoder; 037 038 /** 039 * Constructs a new instance. 040 * 041 * @deprecated Creating an instance without a {@link StringEncoder} leads to a {@link NullPointerException}. Will be 042 * removed in 2.0. 043 */ 044 @Deprecated 045 public StringEncoderComparator() { 046 this.stringEncoder = null; // Trying to use this will cause things to break 047 } 048 049 /** 050 * Constructs a new instance with the given algorithm. 051 * 052 * @param stringEncoder 053 * the StringEncoder used for comparisons. 054 */ 055 public StringEncoderComparator(StringEncoder stringEncoder) { 056 this.stringEncoder = stringEncoder; 057 } 058 059 /** 060 * Compares two strings based not on the strings themselves, but on an encoding of the two strings using the 061 * StringEncoder this Comparator was created with. 062 * 063 * If an {@link EncoderException} is encountered, return <code>0</code>. 064 * 065 * @param o1 066 * the object to compare 067 * @param o2 068 * the object to compare to 069 * @return the Comparable.compareTo() return code or 0 if an encoding error was caught. 070 * @see Comparable 071 */ 072 @Override 073 public int compare(Object o1, Object o2) { 074 075 int compareCode = 0; 076 077 try { 078 Comparable s1 = (Comparable) this.stringEncoder.encode(o1); 079 Comparable s2 = (Comparable) this.stringEncoder.encode(o2); 080 compareCode = s1.compareTo(s2); 081 } catch (EncoderException ee) { 082 compareCode = 0; 083 } 084 return compareCode; 085 } 086 087 }