1.HashMap
1.允许键和值为null
public V put(K key, V value) {
if (key == null)
return putForNullKey(value);
int hash = hash(key.hashCode());
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
}
private V putForNullKey(V value) {
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
if (e.key == null) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(0, null, value, 0);
return null;
}
2.适用于单线程环境,是线程不安全的(resize时)
3.提供了可供应用迭代的键的集合,因此HashMap是快速失败的
HashTable
1.不允许键和值为null
public synchronized V put(K key, V value) {
// Make sure the value is not null
if (value == null) {
throw new NullPointerException();
}
// Makes sure the key is not already in the hashtable.
Entry tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
V old = e.value;
e.value = value;
return old;
}
}
modCount++;
if (count >= threshold) {
// Rehash the table if the threshold is exceeded
rehash();
tab = table;
index = (hash & 0x7FFFFFFF) % tab.length;
}
// Creates the new entry.
Entry<K,V> e = tab[index];
tab[index] = new Entry<K,V>(hash, key, value, e);
count++;
return null;
}
2.适用于多线程环境,线程安全(synchronized )
3.提供了对键的列举,一般认为HashTable是一个遗留类
遗留集合使用Enumeration接口对元素进行遍历,Enumeration接口有两个方法,即hasMoreElements和nextElement。此接口的功能与Iterator接口的功能是重复的,此外,Iterator接口添加了一个可选的移除操作,并使用较短的方法名,新的接口实现应该优先考虑使用Iterator接口而不是Enumeration接口。
hasMoreElements()测试此枚举是否包含更多的元素
nextElement()如果此枚举对象至少还有一个可提供的元素,则返回此枚举的下一个元素