1 16 19 package org.apache.xml.utils; 20 21 28 public class Trie 29 { 30 31 32 public static final int ALPHA_SIZE = 128; 33 34 35 Node m_Root; 36 37 38 private char[] m_charBuffer = new char[0]; 39 40 43 public Trie() 44 { 45 m_Root = new Node(); 46 } 47 48 56 public Object put(String key, Object value) 57 { 58 59 final int len = key.length(); 60 if (len > m_charBuffer.length) 61 { 62 m_charBuffer = new char[len]; 64 } 65 66 Node node = m_Root; 67 68 for (int i = 0; i < len; i++) 69 { 70 Node nextNode = node.m_nextChar[Character.toUpperCase(key.charAt(i))]; 71 72 if (nextNode != null) 73 { 74 node = nextNode; 75 } 76 else 77 { 78 for (; i < len; i++) 79 { 80 Node newNode = new Node(); 81 node.m_nextChar[Character.toUpperCase(key.charAt(i))] = newNode; 83 node.m_nextChar[Character.toLowerCase(key.charAt(i))] = newNode; 84 node = newNode; 85 } 86 break; 87 } 88 } 89 90 Object ret = node.m_Value; 91 92 node.m_Value = value; 93 94 return ret; 95 } 96 97 104 public Object get(final String key) 105 { 106 107 final int len = key.length(); 108 109 112 if (m_charBuffer.length < len) 113 return null; 114 115 Node node = m_Root; 116 switch (len) { 118 case 0 : 122 { 123 return null; 124 } 125 126 case 1 : 127 { 128 final char ch = key.charAt(0); 129 if (ch < ALPHA_SIZE) 130 { 131 node = node.m_nextChar[ch]; 132 if (node != null) 133 return node.m_Value; 134 } 135 return null; 136 } 137 default : 159 { 160 key.getChars(0, len, m_charBuffer, 0); 161 for (int i = 0; i < len; i++) 163 { 164 final char ch = m_charBuffer[i]; 165 if (ALPHA_SIZE <= ch) 166 { 167 return null; 169 } 170 171 node = node.m_nextChar[ch]; 172 if (node == null) 173 return null; 174 } 175 176 return node.m_Value; 177 } 178 } 179 } 180 181 185 class Node 186 { 187 188 191 Node() 192 { 193 m_nextChar = new Node[ALPHA_SIZE]; 194 m_Value = null; 195 } 196 197 198 Node m_nextChar[]; 199 200 201 Object m_Value; 202 } 203 } 204 | Popular Tags |