1 7 package com.ibm.icu.impl; 8 9 import java.util.ArrayList ; 10 import java.util.List ; 11 12 import com.ibm.icu.lang.UCharacter; 13 import com.ibm.icu.text.UTF16; 14 15 19 public class TextTrieMap { 20 25 public TextTrieMap(boolean ignoreCase) { 26 this.ignoreCase = ignoreCase; 27 } 28 29 37 public synchronized Object put(String text, Object o) { 38 CharacterNode node = root; 39 for (int i = 0; i < text.length(); i++) { 40 int ch = UTF16.charAt(text, i); 41 node = node.addChildNode(ch); 42 if (UTF16.getCharCount(ch) == 2) { 43 i++; 44 } 45 } 46 Object prevObj = node.getObject(); 47 node.setObject(o); 48 return prevObj; 49 } 50 51 59 public Object get(String text) { 60 return get(root, text, 0); 61 } 62 63 72 public Object get(String text, int start) { 73 return get(root, text, start); 74 } 75 76 86 private synchronized Object get(CharacterNode node, String text, int index) { 87 Object obj = node.getObject(); 88 if (index < text.length()) { 89 List childNodes = node.getChildNodes(); 90 if (childNodes == null) { 91 return obj; 92 } 93 int ch = UTF16.charAt(text, index); 94 int chLen = UTF16.getCharCount(ch); 95 for (int i = 0; i < childNodes.size(); i++) { 96 CharacterNode child = (CharacterNode)childNodes.get(i); 97 if (compare(ch, child.getCharacter())) { 98 Object tmp = get(child, text, index + chLen); 99 if (tmp != null) { 100 obj = tmp; 101 } 102 break; 103 } 104 } 105 } 106 return obj; 107 } 108 109 116 private boolean compare(int ch1, int ch2) { 117 if (ch1 == ch2) { 118 return true; 119 } 120 else if (ignoreCase) { 121 if (UCharacter.toLowerCase(ch1) == UCharacter.toLowerCase(ch2)) { 122 return true; 123 } 124 else if (UCharacter.toUpperCase(ch1) == UCharacter.toUpperCase(ch2)) { 125 return true; 126 } 127 } 128 return false; 129 } 130 131 private CharacterNode root = new CharacterNode(0); 133 134 boolean ignoreCase; 136 137 140 private class CharacterNode { 141 int character; 142 List children; 143 Object obj; 144 145 150 public CharacterNode(int ch) { 151 character = ch; 152 } 153 154 159 public int getCharacter() { 160 return character; 161 } 162 163 169 public void setObject(Object obj) { 170 this.obj = obj; 171 } 172 173 178 public Object getObject() { 179 return obj; 180 } 181 182 191 public CharacterNode addChildNode(int ch) { 192 if (children == null) { 193 children = new ArrayList (); 194 CharacterNode newNode = new CharacterNode(ch); 195 children.add(newNode); 196 return newNode; 197 } 198 CharacterNode node = null; 199 for (int i = 0; i < children.size(); i++) { 200 CharacterNode cur = (CharacterNode)children.get(i); 201 if (compare(ch, cur.getCharacter())) { 202 node = cur; 203 break; 204 } 205 } 206 if (node == null) { 207 node = new CharacterNode(ch); 208 children.add(node); 209 } 210 return node; 211 } 212 213 218 public List getChildNodes() { 219 return children; 220 } 221 } 222 } 223 | Popular Tags |