java 数据结构之HashTable
HashTable是一个比较早的类,也是一个数组链表的数据结构,跟HashMap特别像,都实现了Map接口,但是HashTable只允许non-null的key或者value,另外HashTable是线程安全的,可以看到HashTable的方法使用了synchronized关键字来修饰,所以是线程安全的,synchronized这个关键字是以后结合java其他的同步技术来说下。
* Java Collections Framework</a>. Unlike the new collection
* implementations, {@code Hashtable} is synchronized. If a
* thread-safe implementation is not needed, it is recommended to use
* {@link HashMap} in place of {@code Hashtable}. If a thread-safe
* highly-concurrent implementation is desired, then it is recommended
* to use {@link java.util.concurrent.ConcurrentHashMap} in place of
* {@code Hashtable}.
简单来说如果不需要线程安全,推荐使用hashMap,效率更高,如果需要使用线程安全,就使用ConcurrentHashMap类,这么说起来其实HashTable有点鸡肋。
另外,HashMap与HashTable还有一个区别就是迭代器的不同,具体看下,先看HashMap的迭代器
private abstract class HashIterator<E> implements Iterator<E> {
Entry<K,V> next; // next entry to return
int expectedModCount; // For fast-fail
int index; // current slot
Entry<K,V> current; // current entry
HashIterator() {
expectedModCount = modCount;
if (size > 0) { // advance to first entry
Entry[] t = table;
while (index < t.length && (next = t[index++]) == null)
;
}
}
public final boolean hasNext() {
return next != null;
}
final Entry<K,V> nextEntry() {
if (modCount != expectedModCount)//当hashMap的结构被修改时候,抛出异常,fail-fast
throw new ConcurrentModificationException();
Entry<K,V> e = next;
if (e == null)
throw new NoSuchElementException();
if ((next = e.next) == null) {
Entry[] t = table;
while (index < t.length && (next = t[index++]) == null)
;
}
current = e;
return e;
}
public void remove() {
if (current == null)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
Object k = current.key;
current = null;
HashMap.this.removeEntryForKey(k);
expectedModCount = modCount;
}
}
可以看到,当hashMap的结构发生改变,也就是迭代HashMa元素时调用put或者remove方法,会抛出ConcurrentModificationException异常。但是你可以使用迭代器的remove方法来移除对象。
HashTable中的迭代器是Enumerator,具体可以看代码。