HashTable特点(jdk1.8)
简单写一写HashTable的特点~
继承树 |
HashTable的继承树如下图:
特点 |
(1)底层使用Entry数组保存元素
(2)默认初始容量是11,加载因子是0.75。
/** * Constructs a new, empty hashtable with a default initial capacity (11) * and load factor (0.75). */
public Hashtable() {
this(11, 0.75f);
}
(3)可以指定初始容量和加载因子。指定初始容量时即按照指定值进行容量分配。
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 Entry<?,?>[initialCapacity];
threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
}
public Hashtable(int initialCapacity) {
this(initialCapacity, 0.75f);
}
(4)线程安全,方法使用synchronized修饰。
(5)具有fail-fast的特征
(6)key和value均不允许为null,否则抛出java.lang.NullPointerException异常。
(7)计算索引的方式为:
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
(8)如果key已经存在,则新value覆盖旧value,并返回旧value。
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;
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);
return null;
}
(9)如果超过扩容阈值threshold(数组容量 * 加载因子),则进行rehash扩容。新数组容量=(原数组容量 << 1) + 1
还没有评论,来说两句吧...