/**
* Returns the number of keys in this hashtable.
*
* @return the number of keys in this hashtable.
*/publicsynchronizedintsize() {
return count;
}
/**
* Tests if this hashtable maps no keys to values.
*
* @return <code>true</code> if this hashtable maps no keys to values;
* <code>false</code> otherwise.
*/publicsynchronizedbooleanisEmpty() {
return count == 0;
}
/**
* Returns an enumeration of the keys in this hashtable.
*
* @return an enumeration of the keys in this hashtable.
* @see Enumeration
* @see #elements()
* @see #keySet()
* @see Map
*/publicsynchronized Enumeration<K> keys() {
returnthis.<K>getEnumeration(KEYS);
}
可以看到,有很多方法都加了synchronized关键字。
以下为截取的一部分HashMap源码
/**
* Returns the number of key-value mappings in this map.
*
* @return the number of key-value mappings in this map
*/publicintsize() {
return size;
}
/**
* Returns <tt>true</tt> if this map contains no key-value mappings.
*
* @return <tt>true</tt> if this map contains no key-value mappings
*/publicbooleanisEmpty() {
return size == 0;
}
然而同步不可避免的是性能会有所下降,所以一般还是用HashMap比较多。
三、Hashtable不允许键值为null,而HashMap则允许
以下为Hashtable的put方法的源码
public synchronized V put(K key, V value) {
// Make sure the value is not nullif (value == null) {
thrownew NullPointerException();
}
// Makes sure the key is not already in the hashtable.
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
@SuppressWarnings("unchecked")
Entry<K,V> entry = (Entry<K,V>)tab[index];
for(; entry != null ; entry = entry.next) {
if ((entry.hash == hash) && entry.key.equals(key)) {
V old = entry.value;
entry.value = value;
return old;
}
}
addEntry(hash, key, value, index);
returnnull;
}