1.源码分析
首先我们来看构造函数:
public Hashtable(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal Load: "+loadFactor);
if (initialCapacity==0)
initialCapacity = 1;
this.loadFactor = loadFactor;
table = new HashtableEntry[initialCapacity];
threshold = (initialCapacity <= MAX_ARRAY_SIZE + 1) ? initialCapacity : MAX_ARRAY_SIZE + 1;
}
public Hashtable() {
this(11, 0.75f);
}
乍一看跟HashMap差不多,其实仔细一看,构造方法就有点不同,首先HashTable的初始容量默认为11,但如果初始容量设为0 则会变成1
接着我们来看put方法:
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.
HashtableEntry tab[] = table;
//key.hashCode
int hash = hash(key);
//2^31= 0x7FFFFFFF
int index = (hash & 0x7FFFFFFF) % tab.length;
for (HashtableEntry<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;
hash = hash(key);
index = (hash & 0x7FFFFFFF) % tab.length;
}
// Creates the new entry.
HashtableEntry<K,V> e = tab[index];
tab[index] = new HashtableEntry<>(hash, key, value, e);
count++;
return null;
}
首先put方法有synchronized关键字,其次,value不能为空,接着 (hash & 0x7FFFFFFF),因为hash是要作为数组的index的,这样可以避免出现下标为负数而出现异常,很明显,index就是hash取table的长度的摸
当count>=threshold时,一开始的时候threshold时其实就是初始容量,接着执行rehash
protected void rehash() {
int oldCapacity = table.length;
HashtableEntry<K,V>[] oldMap = table;
// overflow-conscious code
int newCapacity = (oldCapacity << 1) + 1;
if (newCapacity - MAX_ARRAY_SIZE > 0) {
if (oldCapacity == MAX_ARRAY_SIZE)
// Keep running with MAX_ARRAY_SIZE buckets
return;
newCapacity = MAX_ARRAY_SIZE;
}
HashtableEntry<K,V>[] newMap = new HashtableEntry[newCapacity];
modCount++;
threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
table = newMap;
for (int i = oldCapacity ; i-- > 0 ;) {
for (HashtableEntry<K,V> old = oldMap[i] ; old != null ; ) {
HashtableEntry<K,V> e = old;
old = old.next;
int index = (e.hash & 0x7FFFFFFF) % newCapacity;
e.next = newMap[index];
newMap[index] = e;
}
}
}
概括的说这一步可以称为扩容,容量扩大一倍+1,然后重新的排列里面的元素,HashtableEntry:
protected HashtableEntry(int hash, K key, V value, HashtableEntry<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
通过HashtableEntry构造函数,我们也可以知道Hashtableput元素也是采用的时插头法
接下来来看看get方法:
public synchronized V get(Object key) {
HashtableEntry tab[] = table;
int hash = hash(key);
int index = (hash & 0x7FFFFFFF) % tab.length;
for (HashtableEntry<K,V> e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
return e.value;
}
}
return null;
}
。。。通过上面分析的put方法,get看上去就容易懂了