一、 HashMap
1)底层实现
数组+链表+红黑树(在JDK1.8中如果链表长度大于8的时候才转换为红黑树)
2)是否线程安全
不支持线程的同步,线程不安全,如需同步,可用Collections的synchronizedMap方法或者使用ConcurrentHashMap,调用这个对象的方法使HashMap具有同步的能力。
3)插入值操作过程
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;
}
4) 特点
HashMap最多只允许一条记录的键为null,允许多条记录的值为null,然后和插入效率高,但是插入的数据是无序的,插入、删除和定位元素,HashMap是最好的选择
5)hashmap什么时候进行扩容
当hashmap中的元素个数超过数组大小loadFactor时,就会进行数组扩容,loadFactor的默认值为0.75,也就是说,默认情况下,数组大小为16,那么当hashmap中元素个数超过160.75=12的时候,就把数组的大小扩展为2*16=32,即扩大一倍,然后重新计算每个元素在数组中的位置,而这是一个非常消耗性能的操作。
二、 Hashtable
1)底层实现
它继承自Dictionary类
2)是否线程安全
支持线程的同步,线程安全,即任一时刻只有一个线程能写Hashtable,因此也导致了 Hashtable在写入时会比较慢
Java之HashMap、Hashtable、LinkedHashMap、TreeMap、ConcurrentHashMap简单的区别
最新推荐文章于 2024-06-13 08:37:22 发布