…lines 1–24 unchanged (24 lines)
25 *
26 * @since 3.0
27 * @version $Id$
28 */
29public class LookupTranslator extends CharSequenceTranslator {
30
31 private final HashMap<String, CharSequence> lookupMap;
32 private final int shortest;
33 private final int longest;
34
35 /**
36 * Define the lookup table to be used in translation
37 *
38 * Note that, as of Lang 3.1, the key to the lookup table is converted to a
39 * java.lang.String, while the value remains as a java.lang.CharSequence.
40 * This is because we need the key to support hashCode and equals(Object),
41 * allowing it to be the key for a HashMap. See LANG-882.
42 *
43 * @param lookup CharSequence[][] table of size [*][2]
44 */
45 public LookupTranslator(final CharSequence[]... lookup) {
46 lookupMap = new HashMap<String, CharSequence>();
47 int _shortest = Integer.MAX_VALUE;
48 int _longest = 0;
49 if (lookup != null) {
50 for (final CharSequence[] seq : lookup) {
51 this.lookupMap.put(seq[0].toString(), seq[1]);
52 final int sz = seq[0].length();
53 if (sz < _shortest) {
54 _shortest = sz;
55 }
56 if (sz > _longest) {
57 _longest = sz;
…lines 58–70 unchanged (13 lines)
71 if (index + longest > input.length()) {
72 max = input.length() - index;
73 }
74 // descend so as to get a greedy algorithm
75 for (int i = max; i >= shortest; i--) {
76 final CharSequence subSeq = input.subSequence(index, index + i);
77 final CharSequence result = lookupMap.get(subSeq.toString());
78 if (result != null) {
79 out.write(result.toString());
80 return i;
81 }
82 }
83 return 0;
84 }
85}
86