HashMap部分源码解析

  • 首先说下hashmap的优点:根据key找到元素位置取出元素,若不考虑冲突,可实现随机取值(时间复杂度为1),底层数据结构为数组,为解决hash冲突,使用拉链法,所以数组中存的是链表的首节点,冲突后构成一条单链表;为了提高查询速率,当链表节点个数符合特定条件,会把链表转化成红黑树。对比ArrayList和LinkedList,它们都需要去遍历集合中元素,因为不知道这个值是否存在以及存在哪个位置。
  • 本篇文章主要对HashMap 底层数据结构,扩容,插入元素,获取元素,删除元素源码进行解析。一般哈希表采用除留取余法,为了减少hash冲突会将数组长度为一个质数以达到减少hash冲突,但java实现哈希表是使用2的幂次数作为数组的长度,使用位运算提高检索节点元素效率(因为位运算比%取模运算要快)。

先看一下常量设定

//默认初始容量,是因为底层是数组,所以这个容量为数组的长度
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
//最大的容量
static final int MAXIMUM_CAPACITY = 1 << 30;
//默认负载因子,主要是为了减少hash冲突
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//链表转化成红黑树界定值
static final int TREEIFY_THRESHOLD = 8;
//红黑树退化成链表界定值
static final int UNTREEIFY_THRESHOLD = 6;
//链表转化成树最小容量
static final int MIN_TREEIFY_CAPACITY = 64;

主要数据成员和两个被隐藏了的函数

//hashmap存储结构,Node类型数组
transient Node<K,V>[] table;
//暂时对entrySet()不是很了解,猜测是遍历数组保存在一个set集合中
transient Set<Map.Entry<K,V>> entrySet;
//容器节点个数
transient int size;
//和迭代器fast-fail机制有关
transient int modCount;
//阀值,超出阀值数组将扩容
 int threshold;
 //负载因子
 final float loadFactor;
 //数组元素类型定义
 static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;
        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }
        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }
        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }
		
        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    } 
 //列出这两个函数的目的是利用反射去验证某些实现方法,例如resize()扩容实现
final float loadFactor() { return loadFactor; }
 final int capacity() {
        return (table != null) ? table.length :
            (threshold > 0) ? threshold :
            DEFAULT_INITIAL_CAPACITY;
    }

hashcode()

//将hash值高16位与低16位进行异或运算,实现减少hash冲突
static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
	

HashMap构造器

    //形参 初始大小,负载因子(和扩容相关  size>table.length*loadFactor就扩容)
	//方法里设置了负载因子和阀值,需要注意的是阀值和初始大小有关,最接近initialCapacity的2次幂
	数,例如5,则阀值为8,真正数组的大小并不是initialCapacity,它也是一个最接近
	initialCapacity的2次幂数
	 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);
    }
	//调用上一个构造器,使用默认负载因子0.75
	public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
	//只初始化负载因子
	 public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }
	//构造一个映射关系与指定 Map 相同的新 HashMap。使用默认负载因子,就不深究putMapEntries()
	方法了,前三个构造器数组并未初始化,为null
	public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

构造器中有一个 tableSizeFor()函数,这个函数是扩容的关键,将按照这个函数返回值进行扩容。

static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }
	函数计算返回结果:返回>=cap 最小的2次幂的数 例如cap等于10 16>=最小的2次幂的数。
	函数内部实现的将cap二进制最高位的1向比它低的位传递(由|=实现,例如9二进制数1001>>>1之后
	为0100 再进 行|运算 结果为1101,为了加快传递,下次>>>2(这里>>>4,8,16都没有用上,因为低位
	已经都为1了,可以自己弄一个更大数,规律为每次>>>位数都需要是上次的2倍,跟复制差不多所以是2倍) ,
	运算结果为1111,因为int32位,需要传递小于32大于16次 ),使低位都变成1,然后+1实现进位,这
	个数就是最小的2次幂,当cap刚好为2次幂数,则返回cap,由int n=cap-1;语句实现,先降一位然后进
	位返回原数。
	不想动手实践的,可以参考博客:https://blog.csdn.net/fan2012huan/article/details/51097331

扩容函数resize()

final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
		//旧数组length
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
		//扩容阀值
        int oldThr = threshold;
        int newCap, newThr = 0;
		//已经扩容过,数组length>0
        if (oldCap > 0) {
			//判断数组长度是否大于等于1<<30,一般数组不会有这么大
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
			//扩容为原来2倍,如果旧数组长度大于等于16,则扩容阀值也为原来2倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
		//否则旧阀值大于0 新数组长度为旧阀值
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
			//上诉要求(从没有扩容且阀值没有初始化)都不满足,则新数组长度为16,阀值为默认负载
			因子(0.75)*默认初始数组长度(16)=12
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
		//假如新阀值等于0(从来没有扩容)
        if (newThr == 0) {
			//新阀值=新数组长度*负载因子(或者等于Integer.MAX_VALUE,一般不考虑)
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
		//将新阀值保存到阀值变量中
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
		//开始扩容
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
		//将旧数组的元素迁移到新数组中
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
					//不冲突重新除留取余法
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
					//如果冲突之后是红黑树结构
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
					//冲突是链表,采用两种方法将元素存到新数组中,缩短链表长度,将链表一分为二,
					以高低位区分(e.hash & oldCap,这个要么等于0 低位,要么等于1 高位),低
					位存在原来下标位置,高位存在原来下标+原来数组长度 的位置
                    else { // preserve order
					// lohead 低位头节点,loTail 低位尾节点 hiHead 高位头结点 
					hiTail高位尾节点
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

往集合添加节点元素put()

public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
	
	
	final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
		//判断数组是否存在或者数组是否有元素,若不存在或者没有元素,则扩容
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
		//假如通过hash算出数组下标元素为空,则将元素存入数组中
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
		//否则数组中已有元素,发生哈希冲突
        else {
            Node<K,V> e; K k;
			//假如hash和键相同(这个是在数组上做的判断,下面那个在数组之外做的判断)
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
			//不同,链表处理方法
            else {
                for (int binCount = 0; ; ++binCount) {
					//若键的内容不相同,插入到链表尾部
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
						//链表转换成红黑树
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
					//每次键相同,就判断hash和键是否相同
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
			//当key重复时,更新为新值,返回旧值
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
				//替换旧值
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
				//LinkHashMap有实现该方法,HashMap中该方法体为空,等于没有做操作
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
		//达到阀值扩容
        if (++size > threshold)
            resize();
		//LinkHashMap有实现该方法,HashMap中该方法体为空
        afterNodeInsertion(evict);
        return null;
    }

删除节点元素remove()

 public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }
    
final Node<K,V> removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {
        Node<K,V>[] tab; Node<K,V> p; int n, index;
		//数组不为空且通过hash计算出来的下标元素不为空,将节点赋给p
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (p = tab[index = (n - 1) & hash]) != null) {
				//第一次见这个写法,赋值和声明在同一边,等价于Node<K,V> node=null; Node<K,V> e;node是要返回的节点,找到元素就赋给node
            Node<K,V> node = null, e; K k; V v;
			//找到下标,先和数组中的元素(桶)比较,不满足在比较链表(红黑树)上的元素(bin),满足将p赋给node
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
				//e指向p的下一个元素
            else if ((e = p.next) != null) {
				//红黑树的操作
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
				//链表上的操作
                else {
                    do {
						//找到元素,将e赋值node
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
						//记录当前位置
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
			//判断通过key找到的元素上的value是否与形参value相等
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
				//红黑树的操作					 
                if (node instanceof TreeNode)
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
				//数组上的操作,假如node在数组上,直接将node指向的下个节点放入数组中
                else if (node == p)
                    tab[index] = node.next;
				//链表上的操作 此时p为node的上一个节点,删除node只需要将p节点和node下个节点的元素链接起来(p.next=node.next)
                else
                    p.next = node.next;
                ++modCount;
				//个数减一
                --size;
                afterNodeRemoval(node);
				//找到返回node
                return node;
            }
        }
		//没找到返回null
        return null;
    }

获取节点get

public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
//首先HashMap存储结构是数组,因为hash冲突采用开链法,所以数组元素类型为Node类型,使用链表解决
hash冲突(也可能是红黑树,提高查找效率)
	 final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
		//先判断集合中是否有元素,即Node<K,V>类型数据,且根据hash值找到元素存放在数组的位置
		(下标),判断该位置是否存放元素,若不满足则返回null,
		下标使用(n - 1) & hash(除留取余法,前提n为2次幂数,tableSizeFor()以保证可以n是这
		么一个数)。
		//除留取余实现过程 使用&只能取到<=n-1的数,所以除数是n(数组的length),余数<=n-1,因为
		hash值减去余数是n的倍数(例如 hash 二进制110=6 n=4 22次幂 余数2if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
				//若满足上诉要求,则判断key内容是否相等,若相等返回元素
            if (first.hash == hash && // always check first node,
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
				//若是不相等,则考虑到hash冲突,元素在链表(红黑树)上,查询链表,若存在则返回元素,否则返回null
            if ((e = first.next) != null) {
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

entrySet(),这个方法实现没太弄明白,不过它确实能得到HashMap中所有实例,keySet(),values()实现方式类似。有明白的兄弟希望可以帮我解惑。

//返回set集合,元素为Entry<K,V>类型,而Node<K,V>实现Entry<K,V>接口
	public Set<Map.Entry<K,V>> entrySet() {
        Set<Map.Entry<K,V>> es;
		
        return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
    }
    //假如entrySet为空则会new一个EntrySet出来,
		transient Set<Map.Entry<K,V>> entrySet;由于EntrySet继承了
		AbstractSet<Map.Entry<K,V>>,所以能构造出一个Set<Map.Entry<K,V>>集合对象,但未
		显示调用任何方法将节点遍历到Set集合中,所以不太明白怎么实现的。

    final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
        public final int size()                 { return size; }
        public final void clear()               { HashMap.this.clear(); }
        public final Iterator<Map.Entry<K,V>> iterator() {
            return new EntryIterator();
        }
        public final boolean contains(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry<?,?> e = (Map.Entry<?,?>) o;
            Object key = e.getKey();
            Node<K,V> candidate = getNode(hash(key), key);
            return candidate != null && candidate.equals(e);
        }
        public final boolean remove(Object o) {
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>) o;
                Object key = e.getKey();
                Object value = e.getValue();
                return removeNode(hash(key), key, value, true, true) != null;
            }
            return false;
        }
        public final Spliterator<Map.Entry<K,V>> spliterator() {
            return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0);
        }
        public final void forEach(Consumer<? super Map.Entry<K,V>> action) {
            Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            if (size > 0 && (tab = table) != null) {
                int mc = modCount;
                for (int i = 0; i < tab.length; ++i) {
                    for (Node<K,V> e = tab[i]; e != null; e = e.next)
                        action.accept(e);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }
    }

测试resize()和entrySet()

import java.util.*;
import java.lang.reflect.*;
public class TestHashMap{
	//使用反射得到threshold,capacity,这个可以检验扩容方法resize
	static void testResize(HashMap<String,Integer> m)throws NoSuchFieldException,IllegalAccessException,NoSuchMethodException,InvocationTargetException,InvocationTargetException{
		Field tableField=m.getClass().getDeclaredField("threshold");
		Method method=m.getClass().getDeclaredMethod("capacity");
		method.setAccessible(true);
		tableField.setAccessible(true);
		System.out.println("threshold  :"+tableField.get(m));
		System.out.println("capacity  :"+method.invoke(m));
		m.put("xu",1);
		m.put("wu",2);
		m.put("qu",3);
		m.put("ru",4);
		m.put("tu",5);
		m.put("pu",6);
		System.out.println("threshold  :"+tableField.get(m));
		System.out.println("capacity  :"+method.invoke(m));
		m.put("nu",7);
		
		System.out.println("threshold  :"+tableField.get(m));
		System.out.println("capacity  :"+method.invoke(m));
		method.setAccessible(false);
		tableField.setAccessible(false);
	}
	static void testEntrySet()throws NoSuchFieldException,IllegalAccessException{
		HashMap<String,Integer> hm=new HashMap<String,Integer>();
		Field entryField =hm.getClass().getDeclaredField("entrySet");
		entryField.setAccessible(true);
		System.out.println(entryField.get(hm));
		hm.put("xu",1);
		hm.put("wu",2);
		hm.put("qu",3);
		hm.put("ru",4);
		hm.put("tu",5);
		hm.put("pu",6);
		System.out.println(entryField.get(hm));
		Set s=hm.entrySet();
		
		System.out.println(entryField.get(hm));
		
		Iterator it=hm.entrySet().iterator();
		System.out.println(entryField.get(hm));
		
		
		while(it.hasNext()){
			Map.Entry entry=(Map.Entry)it.next();
			Object key=entry.getKey();
			Object val=entry.getValue();
			System.out.println("key  :"+key+"  val  :"+val);
		}
		
		
	}
	
	public static void main(String[]args)throws NoSuchFieldException,IllegalAccessException,NoSuchMethodException,InvocationTargetException,InvocationTargetException{
		HashMap<String,Integer> m=new HashMap<String,Integer>(5);
		testResize(m);
		System.out.println("==========");
		testEntrySet();
		
	
	}
}
结果:
threshold  :8
capacity  :8
threshold  :6
capacity  :8
threshold  :12
capacity  :16
==========
null
null
[tu=5, ru=4, qu=3, pu=6, xu=1, wu=2]
[tu=5, ru=4, qu=3, pu=6, xu=1, wu=2]
key  :tu  val  :5
key  :ru  val  :4
key  :qu  val  :3
key  :pu  val  :6
key  :xu  val  :1
key  :wu  val  :2
结果分析:
resize():threshold和capacity  相等,表明数组并未初始化,且tableSizeFor()返回的是最小的2次
幂数。若扩容则threshold  *loadFactor=capacity,loadFactor默认值为0.75. 
entrySet():由结果分析,只有在调用entrySet()方法,会将hashmap节点元素存放在set集合中。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值