HashMap特点
- HashMap是基于哈希表的Map接口实现。
- HashMap底层采用的是Entry数组和链表实现。
- HashMap是采用key-value形式存储,其中key是可以允许为null但是只能是一个,并且key不允许重复(如果重复则新值覆盖旧值)。
- HashMap是线程不安全的。
- HashMap存入的顺序和遍历的顺序有可能是不一致的。
- HashMap保存数据的时候通过计算key的hash值来去决定存储的位置
字段
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
//默认初始容量为16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
//最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
//默认负载因子为0.75
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//Hash数组(在resize()中初始化)
transient Node<K,V>[] table;
//ket-value集合
transient Set<Map.Entry<K,V>> entrySet;
//元素个数
transient int size;
//修改次数
transient int modCount;
//容量阈值(元素个数超过该值会自动扩容)
int threshold;
//负载因子
final float loadFactor;
构造方法
/*无参*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
/*传入初始容量*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
/*传入初始容量和负载因子*/
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
/*传入Map*/
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
原文
https://segmentfault.com/a/1190000020468223