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