HashMap jdk1.8基础和源码分析


HashMap是基于哈希表的Map实现

哈希表的特点:关键字 key 和它在表中的存放位置 bucketIndex 之间存在一种确定的关系。即bucketIndex = hash(key)

哈希函数:一般情况下,需要在关键字与它在表中的存储位置之间建立一个函数关系,以f(key)作为关键字为key的记录在表中的位置,通常称这个函数f(key)为哈希函数。

hash : 翻译为“散列”,就是把任意长度的输入,通过散列算法,变成固定长度的输出,该输出就是散列值。这种转换是一种压缩映射,散列值的空间通常远小于输入的空间,不同的输入可能会散列成相同的输出,所以不可能从散列值来唯一的确定输入值。

(好的哈希函数会尽可能地保证计算简单和散列地址分布均匀,但是数组是一块连续的固定长度的内存空间,再好的哈希函数也不能保证得到的存储地址绝对不发生冲突)

hash冲突:关键字 key 和它在表中的存放位置 bucketIndex之间存在一种确定的关系。多个key计算出来的bucketIndex是一样的,即产生哈希冲突,需要存放在一个位置。

源码分析:
HashMap是数组+单列表/红黑树的结构
JDK 1.7及以前版本链表是头插法,JDK1.8链表是尾插法
当 Hash 冲突严重时,在桶上形成的单链表会变的越来越长,这样在查询时的效率就会越来越低,时间复杂度为 O(N)。所以引入了红黑树,当一个桶上值大于一个TREEIFY_THRESHOLD时,单链表转换为红黑树,时间复杂度为O(logN),MIN_TREEIFY_CAPACITY默认为64。

JDK 1.7的分析:

以下是JDK1.8的源码分析:

普通单链表的节点Node

static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;//对key的hashcode值进行hash运算后得到的值,存储在Entry,避免重复计算
        final K key;
        V value;
        Node<K,V> next;//存储指向下一个Node的引用,单链表结构

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }
    }

构造函数HashMap()

只是指定了加载因子loadFactor 或者初始容量,并没有给table分配内存空间。
putVal()中会判断table是否为空,为空则初始化,分配存储空间。

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {
//存储节点的数组
transient Node<K,V>[] table; //用于存储Node节点(Map结构的数据)
//实际存储的节点总数
transient int size;
//门限值,是2的整数次幂,= capacity * loadFactor
int threshold;
//加载因子,默认是0.75
final float loadFactor;

//设置初始容量,加载因子默认为0.75
public HashMap(int initialCapacity) {
   this(initialCapacity, DEFAULT_LOAD_FACTOR); 
}
    
//设置初始容量和加载因子(加载因子默认为0.75)
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); //返回>=initialCapacity,且是2的整数次幂的值
    }

  //默认加载因子为0.75
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

   //是否需要扩容,赋值
    final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        if (s > 0) {
            if (table == null) { // pre-size 初始table容量为0
                float ft = ((float)s / loadFactor) + 1.0F; //
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
                if (t > threshold)
                    threshold = tableSizeFor(t); //返回一个2的整数次幂,且>=t
            }
            else if (s > threshold) //table已经存储过,且需要存储的大于门限值
                resize();
            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);
            }
        }
    }

tableSizeFor(int cap)
返回一个大于等于cap且最接近的2的幂次方整数,如给定15/16,返回2的4次方16,给定17返回32
比如有个int cap。
cap - 1 的 值: : 01000000 0000000 00000000 00000000
n | n右移 1 位:01100000 0000000 00000000 00000000
n | n右移 2 位:01111000 0000000 00000000 00000000
n | n右移 4 位:01111111 1000000 00000000 00000000
n | n右移 8 位:01111111 11111111 10000000 00000000
n | n右移16位:01111111 11111111 11111111 11111111
也就说第一个bit为1的后面所有bit都为1
n + 1 则为大于等于给定整数且最接近的2的幂次方整数

//最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;

	//返回一个大于等于cap且最接近的2的幂次方整数
    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;
    }

get(key) 取操作

如果没有找到匹配key的value,返回null;否则返回value

tab[(n - 1) & hash] 相当于tab[hash],table的索引(0 -> n-1, n = table.length)
因为n是2的整数幂,n -1,即1之后所有bit都是1,&1也为1,例如:8(2的三次幂,1000) -> 0111。
注释里简写为tab[hash]

//如果没有找到匹配key的value,返回null;否则返回node节点的value值
   public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

    // 返回匹配的节点node
    final Node<K,V> getNode(int hash, Object 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不为空,且table[hash]不为空
            if (first.hash == hash && // always check first node,匹配桶的第一个节点
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;    //匹配则返回节点first
            if ((e = first.next) != null) { 
                if (first instanceof TreeNode) //如果是红黑树,则按照树的方式查找
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do { //否则,单链表的结构
                    if (e.hash == hash &&  //链表遍历,去匹配key值和hash值,匹配则返回节点e
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null); //直到链表的尾部
            }
        }
        return null; 
    }

//允许存入key为null的map对象,存放位置index = 0
//key的hashcode,高十六16不变,低16位为高16位与低16位的异或值,保证最终获取的存储位置尽量分布均匀
static final int hash(Object key) { 
     int h;
     return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

put(K key, V value) 插入操作

1、如果table == null, resize() ,table初始化扩容

2、如果table[(n - 1) & hash] 为空,空链表则直接插入

3、如果table[(n - 1) & hash] 的刚好匹配上key,执行步骤5

4、通过p.next不断遍历,如果匹配上key,则break, 执行步骤5,返回oldValue;否则一直遍历到链表的尾部,p.next为空的状态,则将p.next指向新的Node节点(并判断是否需要扩容resize)

5、如果有匹配的key,则用value替代oldValue, 返回oldValue

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

// * @param onlyIfAbsent if true, don't change existing value
// * @param evict if false, the table is in creation mode.
    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;     //如果table尚未初始化,则resize()扩容
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);   //如果bucket的首位置为null,直接放入Node节点
        else { //p是bucket的首节点,先判断首节点,不满足再遍历链表或者红黑树结构
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;    //如果bucket的首位置刚好匹配
            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;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break; //匹配上key值,直接退出循环
                    p = e; // p指向p.next
                }
            }
            if (e != null) { // 存在匹配的key,替换为新的value,并返回oldValue
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null) //onlyIfAbsent为false,则value替换oldValue
                    e.value = value;
                afterNodeAccess(e);
                return oldValue; //返回oldValue
            }
        }
        //如果e == null,不存在匹配的key,尾插法
        ++modCount;
        if (++size > threshold) //如果当前存储的节点总数size,大于门限值,扩容
            resize(); 
        afterNodeInsertion(evict);
        return null;
    }

Node<K,V> newNode(int hash, K key, V value, Node<K,V> next) {
        return new Node<>(hash, key, value, next);
    }

Jdk1.7之前是头插法

  Entry<K,V> e = table[bucketIndex];
  table[bucketIndex] = new Entry<K,V>(hash, key, value, e);

JDK1.8 是尾插法

if ((e = p.next) == null) {
    p.next = newNode(hash, key, value, null);
}

resize() 扩容

包括第一次的初始化操作和扩容(2倍操作)。

  • 如果oldTable为null,指定了initialCapacity,则newCap = tableSizeFor(initialCapacity),newThr = newCap * loadFactor(不指定,loadFactor默认为0.75)

  • 如果oldTable为null,没指定initialCapacity,则newCap = DEFAULT_INITIAL_CAPACITY(16),newThr = DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY(即16 * 0.75)

  • 如果oldTable不为null,newCap = oldCap << 1,newThr = oldThr << 1,两倍方式扩容,table = newTab = (Node<K,V>[])new Node[newCap],oldTable的值迁移到newTable上来。

/**
     * Initializes or doubles table size.  If null, allocates in
     * accord with initial capacity target held in field threshold.
     * Otherwise, because we are using power-of-two expansion, the
     * elements from each bin must either stay at same index, or move
     * with a power of two offset in the new table.
     *
     * @return the table
     */
 final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold; //如果指定了initialCapacity,则等于tableSizeFor(initialCapacity)
        int newCap, newThr = 0;
        if (oldCap > 0) {
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) 
        // 如果指定了initialCapacity,newCap = oldThr = tableSizeFor(initialCapacity)
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY; 
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        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) {c
                    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;
    }

  • HashMap的容量始终是2的整数次幂,默认初始化容量为16。
  • 存储的bucket位置为key.hash() & (n -1) ,也就是取hash值的后n位。
  • 假设原始capacity为2的N次幂 ,扩容两倍为 2的(N+1)次幂,存储位置取决于第N+1位(要么为0,要么为1),后N位位置不变,所以说以前的Node要么存放在相同的bucketIndex位置,要么存放在bucketIndex + oldCapacity位置。
不为空需要扩容时,因为我们使用的是2的整数次幂扩容,以前的Node要么存放在相同的bucketIndex位置,
要么存放在bucketIndex  + oldCapacity位置。因为

oldBucketIndex = (table.length - 1) & hash
newBucktIndex = (newTable.length - 1) & hash
newTable.length 和 table.length是两倍的关系,只有最高一位N不一致
遍历oldTable数组的每一个bucket位置,索引为j,如bucket中存的是个单链表
原来的单链表中的每一个Node的key值,第N位的值为0,则存放位置和以前一致,为j;为1,则存放位置为 j + oldCap

 - 		对链表中的每一个Node进行判断,如果hash & oldCapacity为0,则newTab[j] = loHead
 -      为1则链接在hiHead上。newTab[j + oldCap] = hiHead

remove(Object k) 删除操作

1、如果table不为null且table[(n - 1) & hash]不为空,取出table[(n - 1) & hash] 为p,p为表头;

2.1、如果p刚好能够匹配key,将p赋给node, 执行步骤3;

2.2、否则遍历,此时p会更新为e的上一个节点,如果找到能匹配上的key,e赋值给node,break,执行步骤3(也许不存在匹配的key,则直接返回null)

3、存在node(可匹配上key的这么一个节点),如果node是表头,则table[index] = node.next;否则p.next = node.next,返回node

4、返回 null

    public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }

// @param value the value to match if matchValue, else ignored
// @param matchValue if true only remove if value is equal
// @param movable if false do not move other nodes while removing  
    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;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (p = tab[index = (n - 1) & hash]) != null) {
            //如果table不为空,且bucket位置的首节点p不为空
            Node<K,V> node = null, e; K k; V v;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;    //检查bucket的首节点是否匹配,匹配直接将p赋给node
            else if ((e = p.next) != null) { //e指向p.next
                if (p instanceof TreeNode) //如果是红黑树,按红黑树的方式遍历查找
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
                else {
                    do {    //链表,遍历查找是否存在相同的key,将e赋给node并返回
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            node = e; //e指向p的下一个节点,node != p
                            break;
                        }
                        p = e; // p指向自己的下一个节点,e指向e的下一个节点,直到遍历完成
                    } while ((e = e.next) != null);
                }
            }
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {    
                //如果存在匹配key的node,且不需要匹配value或者value相等
                if (node instanceof TreeNode) //如果是红黑树类型的节点,红黑树的方式移除
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                else if (node == p) //如果首节点就匹配上,将node节点移除
                    tab[index] = node.next;
                else //不是首节点,则将node节点移除
                    p.next = node.next;
                ++modCount;
                --size; 
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;     //如果都没匹配上,返回null
    }

hash(Object key) 二次哈希

如果key为null,则经过hash计算的bucketIndex为0;二次哈希让键值对均匀分布在数组的N个位置之中。

计算索引位置index = (n - 1 ) & hash,只取hash值的低n位,容易发生hash碰撞。
hash ^ (hash >>> 16) ,将高16位的变化反应到低16位,不容易产生hash碰撞些。

位运算(&)效率要比代替取模运算(%)高很多,主要原因是位运算直接对内存数据进行操作,不需要转成十进制,因此处理速度非常快。

只要保证length的长度是2^n的话,就可以实现取模运算了。HashMap中的length默认初始值是16,之后每次扩充为原来的2倍。

 static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

size()返回的是真实存储的Node数目

size() 返回的是真实存储的Node数目,而不是
isEmpty() 也是判断是否有node存储

 // Returns the number of key-value mappings in this map.
    public int size() {
        return size;
    }

	public boolean isEmpty() {
        return size == 0;
    }

关于threshold的一些讨论

  • size是实际存储的节点个数
  • capacity = table.size (数组大小)
  • threShold = capacity * loadFactor (门限值 = 数组大小 * 加载因子)
new HashMap():指定threshold为默认值0.75,不初始化table分配内存空间
resize()初始化table时,capacity = 默认值16,threshold = 16 * 0.75 = 12,table = new Node[capacity]
判断++size > threshold时,resize()扩容时,都以两倍方式扩容,capacity 和 threshold都*2 
HashMap(int initialCapacity)
HashMap(int initialCapacity, float loadFactor)
指定loadFactor,threshold = tableSizeFor(initialCapacity),不初始化table分配内存空间
resize()初始化table时, newCap = oldThr,threshold = newCap * loadFactor 
比方说initialCapacity = 16,loadFactor为默认值0.75,则oldThr = 16,newCap = 16,threshold = 12
判断++size > threshold时,resize()扩容时,都以两倍方式扩容,capacity 和 threshold都*2 

HashMap总结:

  • 可接受空值和空键,空键会默认存储在bucketIndex为0的地方,
  • key值重复可选择性覆盖,put(K key, V value) 返回oldValue;
  • 没有实现同步,是线程不安全的,相对也就效率更快

结构:一个数组Node<K, V>[] table, 每一个Node节点是一个单链表(jdk1.8之后加入了红黑树) (数组存储空间连续,寻址快,插入删除慢;链表存储空间离散,寻址慢,插入删除快)

存储对象 put(K key, V value):根据key的HashCode()值得到数组中的bucket位置,用来存储键值对,当这个bucket位置没有存储过任何内容时,则直接存放;若已经有人占了位置,即两个key的HashCode()值相同,产生了哈希冲突(碰撞),具有同样hashCode()的键值对会存放在同一个bucket位置;假如存在 key 的 equals() 也相同的情况下,则标记为重复键,用新的value 值替代旧的 value值,并返回旧的value值; 否则的话,每个新进来的node对象放在链表的尾部,形成单链表,返回null

取值 get(v key) : 根据key的HashCode()找到bucket位置,如果存在多个,遍历链表,对key的equals() 进行匹配,匹配成功的则返回value。

key需要实现hashCode() 和 equals(),String 源码实现了hashCode() 和 equals方法,所以用的多

扩容:对数组进行扩容,当存储容量size大于threshold时,会创建一个两倍大小容量的bucket,将旧的数组 移动到 新的数组中去。(多线程的情况下会产生条件竞争,同时扩容,不适用多线程情况)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值