Java Collection集合类- HashMap源码分析

简介:

HashMap主要用来存放键值对,它基于哈希表的Map接口实现
JDK 1.8 之前HashMap由数组 + 链表 组成,数组是HashMap的主体 ,链表主要是为了解决哈希冲突而存在的("拉链法"解决冲突),在JDK1.8之后在解决哈希冲突时,当链表长度大于阈值(默认为 8 ),将链表转化为红黑表,减少搜索时间.

底层数据结构


JDk1.8之前

jdk1.8之前HashMap底层是数组和链表的结合在一起使用 链表散列,HashMap 通过key的hashcode经过 扰动函数处理过后得到hash值,然后通过 (n-1) & hash 判断当前存放位置(n为数组长度),如果当前位置存在元素的话,就判断当前元素以及key是否相同,相同直接覆盖,不相同,就用拉链法解决冲突.

hash源码比较 :
1.8

  static final int hash(Object key) {
        int h;    // key.hashCode(); 返回散列值也就是hashCode();					 s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

1.7

static int hash(int h) {
    // 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);
}

1.8的hash方法效率比1.7hash方法效率高

"拉链法"

将链表和数组相结合,创建一个链表数组,数组中每一格都是一个链表,遇到哈希冲突,将冲突的值加到链表中.
在这里插入图片描述
在1.8之后
JDK1.8在解决hash冲突时有了较大的变化,当链表长度大于阈值(默认为8)时,将链表转换为红黑树,减少搜索时间

在这里插入图片描述
类的属性

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {
    // 序列号
    private static final long serialVersionUID = 362498820763181265L;    
    // 默认的初始容量是16
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;   
    // 最大容量
    static final int MAXIMUM_CAPACITY = 1 << 30; 
    // 默认的填充因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    // 当桶(bucket)上的结点数大于这个值时会转成红黑树
    static final int TREEIFY_THRESHOLD = 8; 
    // 当桶(bucket)上的结点数小于这个值时树转链表
    static final int UNTREEIFY_THRESHOLD = 6;
    // 桶中结构转化为红黑树对应的table的最小大小
    static final int MIN_TREEIFY_CAPACITY = 64;
    // 存储元素的数组,总是2的幂次倍
    transient Node<k,v>[] table; 
    // 存放具体元素的集
    transient Set<map.entry<k,v>> entrySet;
    // 存放元素的个数,注意这个不等于数组的长度。
    transient int size;
    // 每次扩容和更改map结构的计数器
    transient int modCount;   
    // 临界值 当实际大小(容量*填充因子)超过临界值时,会进行扩容
    int threshold;
    // 加载因子
    final float loadFactor;
}
  • loadFactor 加载因子

loadFactor加载因子是控制数组存放数据的疏密程度,loadFactor越趋近于1 ,那么数组中存存放的(entry)也就越多,也就越密,也就是会让链表的长度增加,loadFactor越小,也就越趋进于0,数组中存放的(entry)也就越少,也就越稀疏.

loadFactor太大导致查找元素效率低,太小导致数组的利用率低,存放的数据会很分散.

给定的默认容量 16 ,负载因子为 0.75 , Map在使用的过程中不断地存放数据,当数量达到 16 * 0.75 = 12 就需要将当前16的容量进行扩容.

  • threshold (门槛 阈值)

threshold = Capacity * loadFactor .当size > = threshold ,考虑对数组进行扩增.

**Node节点源码: **

static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;   //哈希值,存放元素到hashmap中用来与其他元素的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; }
			//重写hashcode()方法
        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }
		//重写equals()方法
        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;
        }
    }

树节点类源码:

static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
        TreeNode<K,V> parent;  // 父亲节点
        TreeNode<K,V> left; //左
        TreeNode<K,V> right;// 右
        TreeNode<K,V> prev;    // needed to unlink next upon deletion
        boolean red; //颜色
        TreeNode(int hash, K key, V val, Node<K,V> next) {
            super(hash, key, val, next);
        }

        /**
         * Returns root of tree containing this node.
         */
        final TreeNode<K,V> root() {
            for (TreeNode<K,V> r = this, p;;) {
                if ((p = r.parent) == null)
                    return r;
                r = p;
            }
        }

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);
       this.loadFactor = loadFactor;
       this.threshold = tableSizeFor(initialCapacity);
   }

   //创建指定容量的构造函数
   public HashMap(int initialCapacity) {
       this(initialCapacity, DEFAULT_LOAD_FACTOR);
   }

	//默认构造函数
	  public HashMap() {
       this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
   }

   //创建包含另一个<Map>的构造函数
   public HashMap(Map<? extends K, ? extends V> m) {
       this.loadFactor = DEFAULT_LOAD_FACTOR;
       putMapEntries(m, false);
   }

putMapEntries()方法(添加map类型的entry)

    final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();  //保存传入map的size 
        if (s > 0) {
            if (table == null) { // pre-size
            // 未初始化,s为m的实际元素个数
                float ft = ((float)s / loadFactor) + 1.0F;  //计算阈值
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);    // 得到阈值
             //计算得到的t大于阈值,则初始化阈值            
                if (t > threshold)				
                    threshold = tableSizeFor(t);
            }
		//已经初始化,并且m元素大于阈值,则初始化阈值
            else if (s > threshold)
                resize();
			// 将m中所有的元素添加到HashMap中
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                putVal(hash(key), key, value, false, evict);
            }
        }
    }

PUT方法

  • 如果定位到的数组位置没有元素,就直接插入
  • 如果定位到的数组位置有元素就和要插入的key比较,如果key相同就直接覆盖,如果key不相同,就判断P是否是一个树节点,如果是就调用 e = ()(TreeNode(K,V)p).putTreeval(this,tab,key,value)将元素添加.如果不是就遍历链表插入(尾插).

JDK1.7 put方法的代码

public V put(K key, V value)
    if (table == EMPTY_TABLE) { 
    inflateTable(threshold); 
}  
    if (key == null)
        return putForNullKey(value);
    int hash = hash(key);
    int i = indexFor(hash, table.length);
    for (Entry<K,V> e = table[i]; e != null; e = e.next) { // 先遍历
        Object k;
        if (e.hash == hash && ((k = e.key) == key || key.equals(k)))  //首先判断hash值是否相同,在判断key值
        {
            V oldValue = e.value;
            e.value = value;
            e.recordAccess(this);
            return oldValue; 
        }
    }

    modCount++;
    addEntry(hash, key, value, i);  // 再插入
    return null;
}

JDK1.8的put()方法

   final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;

		// table未初始化或者长度为0 ,进行扩容
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;

		//(n-1) & hash 确定元素存放在哪个桶中,如果桶为空,将新生成的节点放入桶中
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
			//比较第一个元素(数组中的结点)的hash值相等,key相等
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                //将第一个元素赋值给e,用e来记录
                e = p;
			// hash值不相等,key值不相等,为红黑树节点
            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;
                    }
					// 判断节点中的key 与插入新元素的key值是否相等
					
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        //相等跳出循环

					break;
					//用于遍历桶中的链表,与前面的 e = p.next 结合,可以遍历链表
					p = e;
                }
            }
			// 表示在桶中找到key值,hash值与插入元素相同的点
            if (e != null) { // existing mapping for key
				//记录e的value
				V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
					// onlyIfAbsent为false或者旧值为null

				//用新值替换旧值
                    e.value = value;
				//访问后回调
                afterNodeAccess(e);
                return oldValue;
            }
        }

		//结构性修改
        ++modCount;

		//实际大小大于阈值则扩容
        if (++size > threshold)
            resize();
		//插入后回调
        afterNodeInsertion(evict);
        return null;
    }

get()方法

    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

    final Node<K,V> getNode(int hash, Object key) { // 传入key的hash &  key
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {    // 判断table 数组不为空,并且传入hash对应的桶的first节点不为空
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k)))) // 传入的hash与first的hash相同并且key与first的key也相同
                return first;
			//桶中不止一个节点
            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;
    }

resize() hashMap的扩容机制

    final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length; //保存oldTable.length
        int oldThr = threshold; //保存old.threshold
        int newCap, newThr = 0;
        if (oldCap > 0) {

		//超过最大值就不再扩充了
            if (oldCap >= MAXIMUM_CAPACITY) { 
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
			//没超过最大值就扩充为原来的2倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                     
                newThr = oldThr << 1; // double threshold 阈值也变为2倍
        }
        else if (oldThr > 0) // 初始容量设置为阈值
            newCap = oldThr;
        else {               // 初始阈值为0表示使用默认值
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
		//计算新的resize 上限
        if (newThr == 0) {
            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);
                    else { // preserve order
                        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;
    }

常见问题

为什么重写equals一定要重写hashcode?

在这里插入图片描述
在这里插入图片描述
首先这两个函数都是Object类中的方法,equals比较的就是对象的内存地址.

hashCode是本地方法,散列值是根据对象的内存地址经过哈希算法得来的

people A = new people("阿三",19);
people B = new people("阿三",19);

现在有两个对象,如何使A.equals(B) 返回的为true?

  1. 如果两个对象相同(即equals返回true) , hashCode 一定相等;但是两个hashCode相等时,两个对象却不一定是equals
  2. 由于为了提高程序的执行效率才实现了hashCode方法,先进行hashCode比较,如果不同,就没有必要进行equals比较了,这样就大大的减少了equals的使用次数,从而效率得到提高.
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值