屌丝程序员的奋斗之路现在开始
java集合这一块无论在面试或在写代码中,我们都会接触到,所以java集合是特别重要的,其中HashMap更是被我们经常用到。
一.概括
HashMap是用键值对的既已key-value的形式来存储值的,当然这只是展现给大家的一种表象,key和value都可以为空,但是key不能重复,HashMap不是现线安全的,如果想让HashMap变成现线安全的,可以调用Collections的静态方法synchronized方法。其实HashMap是用一个动态数组和多个链表来存放key-value的,key-value不是直接放在数组和链表里面的,key-value是被一个叫Entry的对象给封装了,所以动态数据和链表里面是存放的Entry对象的。
二.HashMap的数据结构
HashMap可以说是由一个动态数组和多个链表组成,链表是接在每一个数组单元下面的,动态数组和链表中存储的单元是一个叫Entry的对象,从下面的图中可以很直观的看出HashMap的数据结构,其中每一个单元格存储的就是Entry对象了,这一个Entry对象是HashMap的一个静态类
Entry源代码
- static class Entry<K,V> implements Map.Entry<K,V> {
- final K key;
- V value;
- Entry<K,V> next;//指向一下个Entry对象,他是为解决hash冲突而存在的。
- int hash;
- /**
- * Creates new entry.
- */
- Entry(int h, K k, V v, Entry<K,V> n) {
- value = v;
- next = n;
- key = k;
- hash = h;
- }
- public final K getKey() {
- return key;
- }
- public final V getValue() {
- return value;
- }
- public final V setValue(V newValue) {
- V oldValue = value;
- value = newValue;
- return oldValue;
- }
- public final boolean equals(Object o) {
- if (!(o instanceof Map.Entry))
- return false;
- Map.Entry e = (Map.Entry)o;
- Object k1 = getKey();
- Object k2 = e.getKey();
- if (k1 == k2 || (k1 != null && k1.equals(k2))) {
- Object v1 = getValue();
- Object v2 = e.getValue();
- if (v1 == v2 || (v1 != null && v1.equals(v2)))
- return true;
- }
- return false;
- }
- public final int hashCode() {
- return (key==null ? 0 : key.hashCode()) ^
- (value==null ? 0 : value.hashCode());
- }
- public final String toString() {
- return getKey() + "=" + getValue();
- }
- /**
- * This method is invoked whenever the value in an entry is
- * overwritten by an invocation of put(k,v) for a key k that's already
- * in the HashMap.
- */
- void recordAccess(HashMap<K,V> m) {
- }
- /**
- * This method is invoked whenever the entry is
- * removed from the table.
- */
- void recordRemoval(HashMap<K,V> m) {
- }
- }
从Entry的属性中看到了我们所熟悉的key和value,没错,这就是我们在用HashMap的时候所要接触到的key,value,Entry对key-value进行了封装,我们再看看Enrty的next属性,存储的就是指向下一个对象的指针,当然java是没有指针这一说的,我觉得在这里将它当成指针更好理解,next在出现hash冲突的时候会发生作用,现在我们再看看上面的那一张图,现在知道为什么那些绿色的链表是怎么连接起来的了吧,就是通过Entry的next属性指向下一个Entry对象连接起来的,所以在HashMap源码中是看不到动态链表的定义,但是它确实是存在的。
三.HashMap的API
1.HashMap的相关属性
- /**
- * HashMap中数组的默认大小是16
- */
- static final int DEFAULT_INITIAL_CAPACITY = 16;
- /**
- * 数组的最大长度
- */
- static final int MAXIMUM_CAPACITY = 1 << 30;
- /**
- * 默认的加载因子是0.75
- */
- static final float DEFAULT_LOAD_FACTOR = 0.75f;
- /**
- * 存放Entry对象的数组,也是HashMap存放数据的地方
- */
- transient Entry<K,V>[] table;
- /**
- * HashMap的存入值得个数,注意:他和数组的大小是没有关系的
- */
- transient int size;
- /**
- * 边界值 <span style="font-family: Arial, Helvetica, sans-serif;">边界值=HahsMap的容量*加载因子</span>
- * @serial
- */
- int threshold;
- /**
- *加载因子
- * @serial
- */
- final float loadFactor;
边界值=数组大小*加载因子
当HashMap所存储对象的个数超过边界值的时候就会对数组进行扩容,例如HashMap默认的加载因子是0.75,数组默认的大小是16,所以边界值是12,当我们在HashMap中存储的值大于等于12的时候,HashMap会对数组table进行2倍的扩容。
2.HashMap的构造方法
- /**
- *给数组设置初始容量和加载因子
- */
- 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);
- // Find a power of 2 >= initialCapacity
- int capacity = 1;
- /*
- *将数组的容量设置为大于初始容量的最小2次幂
- *例如你给HashMap设置的初始容量是20,那HashMap会自动将容量变为32
- */
- while (capacity < initialCapacity)
- capacity <<= 1;
- this.loadFactor = loadFactor;
- threshold = (int)Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
- table = new Entry[capacity];
- useAltHashing = sun.misc.VM.isBooted() &&
- (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
- init();
- }
- /**
- *如果只设置HashMap初始大小,就用默认的加载因子:0.75
- */
- public HashMap(int initialCapacity) {
- this(initialCapacity, DEFAULT_LOAD_FACTOR);
- }
- /**
- *给HashMap设置成默认的大小:16,默认的加载因子0.75
- */
- public HashMap() {
- this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
- }
- /**
- *将Map集合存入HashMap
- */
- public HashMap(Map<? extends K, ? extends V> m) {
- this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
- DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
- putAllForCreate(m);
- }
3.HahMap的hash算
看的不是太懂,需要知道HahMap就是根据key值来进行hash计算的
- /**
- *HashMap的hash算法
- */
- inal int hash(Object k) {
- int h = 0;
- if (useAltHashing) {
- if (k instanceof String) {
- return sun.misc.Hashing.stringHash32((String) k);
- }
- h = hashSeed;
- }
- h ^= k.hashCode();
- // This function ensures that hashCodes that differ only by
- // constant multiples at each bit position have a bounded
- // number of collisions (approximately 8 at default load factor).
- h ^= (h >>> 20) ^ (h >>> 12);
- return h ^ (h >>> 7) ^ (h >>> 4);
- }
4.HahMap的取值方法:get(Object key)
- public V get(Object key) {
- if (key == null)
- return getForNullKey();
- Entry<K,V> entry = getEntry(key);
- return null == entry ? null : entry.getValue();
- }
- final Entry<K,V> getEntry(Object key) {
- //对key进行hash计算得到hash值
- int hash = (key == null) ? 0 : hash(key);
- //再用hash值对数据长队进行取模运算得到key在数组的存储位置,再遍历以数组这个位置为头结点的链表
- for (Entry<K,V> e = table[indexFor(hash, table.length)];e != null;e = e.next) {
- Object k;
- //先去比较key的hash值是否相等,相等再去比较key值是否相等,如果两个都相等,才算找到了
- if (e.hash == hash &&
- ((k = e.key) == key || (key != null && key.equals(k))))
- return e;
- }
- return null;
- }
再看看getForNullKey这个特殊的方法
- private V getForNullKey() {
- for (Entry<K,V> e = table[0]; e != null; e = e.next) {
- if (e.key == null)
- return e.value;
- }
- return null;
- }
5.HahMap的存值方法:V put(K key, V value)
put方法的整个处理流程是:计算key的hash值,根据hash值获得key在table数组中的索引位置,然后迭代该key处的Entry链表(我们暂且理解为链表),若该链表中存在一个这个的key对象,那么就直接替换其value值即可,否则在将改key-value节点插入该index索引位置处。如下:
首先我们假设一个容量为5的table,存在8、10、13、16、17、21。他们在table中位置如下:
然后我们插入一个数:put(16,22),key=16在table的索引位置为1,同时在1索引位置有两个数,程序对该“链表”进行迭代,发现存在一个key=16,这时要做的工作就是用newValue=22替换oldValue16,并将oldValue=16返回。
在put(33,33),key=33所在的索引位置为3,并且在该链表中也没有存在某个key=33的节点,所以就将该节点插入该链表的第一个位置。
- public V put(K key, V value) {
- if (key == null)
- return putForNullKey(value);
- int hash = hash(key);
- /*
- *用数组长度对key的hash值进行取模运算,得到key对应数组的某一个位置
- *再对以这个数组元素为头结点的链表进行遍历
- */
- int i = indexFor(hash, table.length);
- for (Entry<K,V> e = table[i]; e != null; e = e.next) {
- Object k;
- //如果HahMap中有key的存在,就将新的value替换旧的value
- if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
- V oldValue = e.value;
- e.value = value;
- //这个方法没有做任何操作
- e.recordAccess(this);
- return oldValue;
- }
- }
- modCount++;
- //将新添加的key—value放在table[i]的位置
- addEntry(hash, key, value, i);
- return null;
- }
- static int indexFor(int h, int length) {
- return h & (length-1);
- }
addEntry方法
- void addEntry(int hash, K key, V value, int bucketIndex) {
- //先比较size和边界值的大小
- if ((size >= threshold) && (null != table[bucketIndex])) {
- //如果当size大于等于边界值的时候,会对数组进行2倍扩容
- resize(2 * table.length);
- hash = (null != key) ? hash(key) : 0;
- //从新计算key-value存放到数组的地方
- bucketIndex = indexFor(hash, table.length);
- }
- //将新加入的key-value放入到数组中
- createEntry(hash, key, value, bucketIndex);
- }
- //将新加入的key-value放到table的数组中,再将新加入的Entry的next指向数组原来的位置的值,这样就形成了链表
- void createEntry(int hash, K key, V value, int bucketIndex) {
- Entry<K,V> e = table[bucketIndex];
- table[bucketIndex] = new Entry<>(hash, key, value, e);
- size++;
- }
resize 方法,对数组进行扩容
- void resize(int newCapacity) {
- Entry[] oldTable = table;
- int oldCapacity = oldTable.length;
- if (oldCapacity == MAXIMUM_CAPACITY) {
- threshold = Integer.MAX_VALUE;
- return;
- }
- Entry[] newTable = new Entry[newCapacity];
- boolean oldAltHashing = useAltHashing;
- useAltHashing |= sun.misc.VM.isBooted() &&
- (newCapacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
- boolean rehash = oldAltHashing ^ useAltHashing;
- transfer(newTable, rehash);
- table = newTable;
- threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
- }
transfer 方法,从新计算原来数组的元素在新数组元素中的位置
- void transfer(Entry[] newTable, boolean rehash) {
- int newCapacity = newTable.length;
- //遍历table数组
- for (Entry<K,V> e : table) {
- //遍历以数组元素为头结点的链表
- while(null != e) {
- Entry<K,V> next = e.next;
- if (rehash) {
- e.hash = null == e.key ? 0 : hash(e.key);
- }
- //从新计算e在新数组的位置
- int i = indexFor(e.hash, newCapacity);
- //e的next指向原先newTable[i]
- //这里原先的作者应该写错了,e.next应该指向新的newTable[i]处的值
- e.next = newTable[i];
- //将e放入数组新的位置
- newTable[i] = e;
- e = next;
- }
- }
- }
总结一下HashMap的存值的过程
1.首先定位key对应数组中的某一个位置
2.在遍历一下以这个位置的元素为表头的链表
3.查看这个链表中是否有同样的key值
3.1 如果有,就用的新的value替换旧的value,到此就结束了
3.2如果没有,就将新的key-value放入到数组中
4.如果要放到数组中,首先会判断HashMap存储的值得个数是否大于等于边界值
4.1 如果大于边界值,会对数组进行2倍扩容,扩容后会重新计算以前HashMap在新的数组中的位置
5.将新加入的Entry放入到根据对数组相应的位置上,再让Entry的next属性指向原来的数组元素
四.总结
HashMap的数据结构就是由一个数组和多个链表组成的,数组和链表中存储的元素是Entry对象,Entry中有key,value,next,hashCode这几个属性,我们向HashMap中存放key-valu的其实是存入到了Entry对象中了。
HashMap是对key的hashcode进行hash计算得到一个hash值,再用这个hash值与数组长度减一进行于运算,得出key存在数组中的某一个位置,如果数组的这个位置已经有值了,这就产生了所谓的hash冲突,HashMap会将新加入的Entry放在数组中,并让Entry的next指向以前的数组元素,这样就在这里产生了链表。
在新加入元素的时候,当HashMap存储值的个数即size大于或等于边界值的时候,就会对数组进行2倍扩容,这里就是HashMap比较消耗新能的地方了,因为扩容后不仅要遍历整个HashMap,而且还要重新计算每个元素在新的数组中的位置。所以我们在初始化HashMap的时候可以指定数组的大小,尽量减少数组扩容。