1.特点
HashTable可以键值对
形式的数据,key和value 都不能为null
。同时通过synchronized给put和get方法加锁
,保证线程的安全。但是效率低。
原因:
当多个线程执行put方法,put方法进行了加锁操作,这里锁住的实例对象,所以其他线程无法进行同步操
作。
2.构造函数
/* The number of times this Hashtable has been structurally modified
* Structural modifications are those that change the number of entries * in the Hashtable or otherwise modify its internal structure (e.g.,
* rehash). This field is used to make iterators on Collection-views of
* the Hashtable fail-fast. (See ConcurrentModificationException).
*
* hashtable修改的次数 如:add remove clear
*/
private transient int modCount = 0;
//数组对象
private transient Entry<?,?>[] table;
//阈值,用于扩容
private int threshold;
//负载因子
private float loadFactor;
public Hashtable() {
// public Hashtable(int initialCapacity, float loadFactor)
this(11, 0.75f);
}
3.put方法
给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.
Entry<?,?> tab[] = table;
//key不能为null
int hash = key.hashCode();
//计算数据的index
int index = (hash & 0x7FFFFFFF) % tab.length;
@SuppressWarnings("unchecked")
Entry<K,V> entry = (Entry<K,V>)tab[index];
for(; entry != null ; entry = entry.next) {
//如果已经存在key,覆盖value
if ((entry.hash == hash) && entry.key.equals(key)) {
V old = entry.value;
entry.value = value;
return old;
}
}
//添加新的entry
addEntry(hash, key, value, index);
return null;
}
private void addEntry(int hash, K key, V value, int index) {
Entry<?,?> tab[] = table;
if (count >= threshold) {
// Rehash the table if the threshold is exceeded
rehash();
tab = table;
hash = key.hashCode();
index = (hash & 0x7FFFFFFF) % tab.length;
}
// Creates the new entry.
@SuppressWarnings("unchecked")
Entry<K,V> e = (Entry<K,V>) tab[index];
tab[index] = new Entry<>(hash, key, value, e);
count++;
modCount++;
}
4.get方法
public synchronized V get(Object key) {
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
return (V)e.value;
}
}
return null;
}