关于Hashtable和HashMap, Vector和ArrayList
在功能上讲Hashtable和HashMap, Vector和ArrayList有着几乎相同的功能。他们的主要区别在于:
Hashtable和HashMap的区别,先看put方法的源代码
Hashtable
public synchronized V put(K key, V value) {// Make sure the value is not nullif (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; }
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; }
HashMap hm = new HashMap();hm.put(null, null);Hashtable ht = new Hashtable();ht.put("OK", null);ht.put(null, "OK");