fork download
  1. class Ideone
  2. {
  3. public static void main(String[] args)
  4. {
  5. Hashtable<String, Integer> table =
  6. new Hashtable<String, Integer>();
  7. System.out.println(table.set("HOGE", Integer.valueOf(123)));
  8. System.out.println(table.set("HOGE", Integer.valueOf(345)));
  9. System.out.println(table.set("HAGE", Integer.valueOf(555)));
  10. System.out.println(table.set("abcd", Integer.valueOf(999)));
  11. System.out.println(table.set("xyz0", Integer.valueOf(111)));
  12.  
  13. Iterator<Integer> itr = table.items();
  14. while (itr.hasNext())
  15. {
  16. System.out.println(itr.next());
  17. }
  18. }
  19.  
  20. static interface Iterator<T>
  21. {
  22. boolean hasNext();
  23. T next();
  24. }
  25.  
  26. static class Hashtable<K,T>
  27. {
  28. static class List
  29. {
  30. public List next = null;
  31. public Object key = null;
  32. public Object obj = null;
  33. public List(Object key, Object obj)
  34. {
  35. this.key = key;
  36. this.obj = obj;
  37. }
  38. }
  39.  
  40. static final int TABLE_SIZE = 32;
  41.  
  42. List[] table = null;
  43. int count = 0;
  44.  
  45. {
  46. table = new List[TABLE_SIZE];
  47. }
  48.  
  49. public int getCount()
  50. {
  51. return count;
  52. }
  53.  
  54. public boolean set(K key, T item)
  55. {
  56. if (key == null || item == null)
  57. {
  58. return false;
  59. }
  60. int h = key.hashCode() % TABLE_SIZE;
  61. if (table[h] == null)
  62. {
  63. table[h] = new List(key, item);
  64. }
  65. else
  66. {
  67. List list = table[h];
  68. for (;;)
  69. {
  70. if (key.equals(list.key))
  71. {
  72. return false;
  73. }
  74. if (list.next == null)
  75. {
  76. break;
  77. }
  78. else
  79. {
  80. list = list.next;
  81. }
  82. }
  83. list.next = new List(key, item);
  84. }
  85. ++count;
  86. return true;
  87. }
  88.  
  89. public Iterator<T> items()
  90. {
  91. return new Iterator<T>()
  92. {
  93. List[] t = table;
  94. int c = count;
  95. int i = 0;
  96. List list = null;
  97. @Override
  98. public boolean hasNext()
  99. {
  100. return c > 0;
  101. }
  102. @Override
  103. public T next()
  104. {
  105. if (c == 0)
  106. {
  107. return null;
  108. }
  109. List result = null;
  110. if (list == null)
  111. {
  112. for ( ; i < TABLE_SIZE; ++i)
  113. {
  114. if (t[i] != null)
  115. {
  116. result = t[i];
  117. ++i;
  118. break;
  119. }
  120. }
  121. }
  122. else
  123. {
  124. result = list;
  125. }
  126. if (result == null)
  127. {
  128. return null;
  129. }
  130. list = result.next;
  131. --c;
  132. return (T)result.obj;
  133. }
  134. };
  135. }
  136. }
  137. }
Success #stdin #stdout 0.08s 380160KB
stdin
Standard input is empty
stdout
true
false
true
true
true
999
123
555
111