public void clear() { int len = table.length; for (int i=0;i < len; i++) table[i] = null; modCount++; hashTableSize = 0; }
public boolean contains(Object item) { int index = (item.hashCode() & Integer.MAX_VALUE) % table.length; Entry<T> entry; entry = table[index]; while (entry != null) { if (entry.value.equals(item)) return true; entry = entry.next; } return false; }
public boolean isEmpty() { return hashTableSize == 0; }
public Iterator<T> iterator() { return new MyIterator(); }
public int size() { return hashTableSize; }
public Object[] toArray() { Object[] arr = new Object[hashTableSize]; Iterator<T> iter = iterator(); for(int i = 0; iter.hasNext(); i++) arr[i] = iter.next(); return arr; }
public String toString() { int max = hashTableSize - 1; StringBuffer buf = new StringBuffer(); Iterator<T> iter = iterator();
buf.append("["); for (int i = 0; i <= max; i++) { buf.append(iter.next());
if (i < max) buf.append(", "); } buf.append("]"); return buf.toString(); }
private class MyIterator implements Iterator<T> {
Entry<T> next; int expectedModCount; int index; T lastReturned;
//构造函数 MyIterator() { int i = 0; Entry<T> n = null; expectedModCount = modCount; if(hashTableSize != 0) { while(i < table.length && ((n = table[i]) == null)) i++; } next = n; index = i; lastReturned = null; }
public boolean hasNext() { return next != null; }
public T next() { if (modCount != expectedModCount) throw new ConcurrentModificationException();
Entry<T> entry = next;
if (entry == null) throw new NoSuchElementException(); lastReturned = entry.value; Entry<T> n = entry.next; int i = index; if (n == null) { i++; while (i < table.length && ((n = table[i]) == null)) i++; } index = i; next = n; return lastReturned; }
public void remove() { // check for a missing call to next() or previous() if (lastReturned == null) throw new IllegalStateException( "Iterator call to next() " + "required before calling remove()"); if (modCount != expectedModCount) throw new ConcurrentModificationException();
// remove lastReturned by calling remove() in Hash. // this call will increment modCount Hash.this.remove(lastReturned); expectedModCount = modCount; lastReturned = null; }