HashMap Hashtableの違い
2257 ワード
まず2つのクラスの定義を見てみましょう
public class Hashtable
extends Dictionary
implements Map, Cloneable, java.io.Serializable
public class HashMap
extends AbstractMap
implements Map, Cloneable, Serializable
HashtableはDictiionaryから され、HashMapはAbstractMapから されていることがわかります.
Hashtableのputメソッドは のとおりです. public synchronized V put(K key, V value) { //###### 1
// Make sure the value is not null
if (value == null) { //###### 2
throw new NullPointerException();
}
// Makes sure the key is not already in the hashtable.
Entry tab[] = table;
int hash = key.hashCode(); //###### 3
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry 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 e = tab[index];
tab[index] = new Entry(hash, key, value, e);
count++;
return null;
}
1メソッドは の 2メソッドvalue=null 3メソッドはkeyのhashCodeメソッドを び し、key=nullの 、 のポインタ HashMapのputメソッドは のように されます.
public V put(K key, V value) { //###### 1
if (key == null) //###### 2
return putForNullKey(value);
int hash = hash(key.hashCode());
int i = indexFor(hash, table.length);
for (Entry 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;
}
1メソッドが である 2メソッドはkey=null 3メソッドがvalueを び していないのでnullを する
:Hashtableにはcontainsメソッドがあり、 を きやすいので、HashMapではすでに されています.もちろん、2つのクラスはcontainsKeyとcontainsValueメソッドを しています.