Guest User

Untitled

a guest
Jul 19th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. /**
  2. * High performance string map.
  3. * <br/>
  4. * <br/>
  5. * Please <i>note</i> that:
  6. * <ul>
  7. * <li>The key should not be null.</li>
  8. * <li>The key should not be empty.</li>
  9. * <li>The key should contains <b>only ASCII</b> characters.</li>
  10. * <li>The value should not be null.</li>
  11. * </ul>
  12. * <b>No runtime validation is provided in favor of performance.</b>
  13. */
  14. public class TrieMap<T> {
  15.  
  16. private static class Node<T> {
  17.  
  18. @SuppressWarnings("unchecked")
  19. Node<T>[] next = new Node[128];
  20.  
  21. T value;
  22. }
  23.  
  24. private Node<T> root = new Node<T>();
  25.  
  26. /**
  27. * Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.
  28. *
  29. * @param key Key with which the specified value is to be associated.
  30. * @param value Value to be associated with the specified key.
  31. */
  32. public void put(String key, T value) {
  33. Node<T> node = root;
  34. for (int i = 0; i < key.length(); i++) {
  35. int c = key.charAt(i);
  36. if (node.next[c] == null) {
  37. node.next[c] = new Node<T>();
  38. }
  39. node = node.next[c];
  40. }
  41. node.value = value;
  42. }
  43.  
  44. /**
  45. * Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
  46. *
  47. * @param key The key whose associated value is to be returned.
  48. * @return The value to which the specified key is mapped, or null if this map contains no mapping for the key.
  49. */
  50. public T get(String key) {
  51. Node<T> node = root;
  52. for (int i = 0; i < key.length(); i++) {
  53. int c = key.charAt(i);
  54. if (node.next[c] == null) {
  55. return null;
  56. }
  57. node = node.next[c];
  58. }
  59. return node.value;
  60. }
  61.  
  62. /**
  63. * Returns true if this map contains a mapping for the specified key.
  64. *
  65. * @param key The key whose presence in this map is to be tested.
  66. * @return True if this map contains a mapping for the specified key.
  67. */
  68. public boolean has(String key) {
  69. return get(key) == null;
  70. }
  71. }
Add Comment
Please, Sign In to add comment