HashMap

HashMap

JDK1.8 之前 HashMap 由 数组+链表 组成的,数组是 HashMap 的主体,链表则是主要为了解决哈希冲突而存在的(“拉链法”解决冲突)。 JDK1.8 以后的 HashMap 在解决哈希冲突时有了较大的变化,当链表长度大于阈值(默认为 8)(将链表转换成红黑树前会判断,如果当前数组的长度小于 64,那么会选择先进行数组扩容,而不是转换为红黑树)时,将链表转化为红黑树,以减少搜索时间。

HashMap 默认的初始化大小为 16。之后每次扩充,容量变为原来的 2 倍。并且, HashMap 总是使用 2 的幂作为哈希表的大小。

HashMap中可以存储一个以null为键值的键值对。

HashMap的遍历方法

  • entrySet()

  • keySet()

  • values()

  • 迭代器

三种基本方式

Set<Map.Entry<Integer, Integer>> entries = map.entrySet();
for (Map.Entry<Integer, Integer> entry : entries) {
    int key = entry.getKey();
    int value = entry.getValue();
    System.out.println(key + ":" + value);
}

Set<Integer> keySet = map.keySet();
for (int k : keySet) {
    System.out.println(k);
}

Collection<Integer> values = map.values();
for (int value : values) {
    System.out.println(value);
}

使用forEach

//两种方式都可以遍历map,第一种方法更直观,但使用stream流可以进行更多的操作比如过滤等
map.entrySet().forEach(entry -> {
    int key = entry.getKey();
    int value = entry.getValue();
});

map.entrySet().stream().forEach(entry -> {
    int key = entry.getKey();
    int value = entry.getValue();
});

使用迭代器和不用迭代器遍历的区别

  • 迭代器遍历Map的EntrySet时可以使用remove()方法删除遍历到的元素,而直接遍历EntrySet时不能删除元素。
  • 直接遍历EntrySet时代码更简洁,性能更高。
  • 迭代器遍历map适用于需要删除元素的情况,只遍历直接遍历EntrySet。
Set<Map.Entry<Integer, Integer>> entries = map.entrySet();
for (Map.Entry<Integer, Integer> entry : entries) {
    int key = entry.getKey();
    int value = entry.getValue();
    System.out.println(key + ":" + value);
}

System.out.println("===============");

Iterator<Map.Entry<Integer, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
    Map.Entry<Integer, Integer> it = iterator.next();
    int key = it.getKey();
    int value = it.getValue();
    System.out.println(key + ":" + value);
}

底层数据结构

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {

    //序列号
    private static final long serialVersionUID = 362498820763181265L;
    //默认初始化容量
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
    //最大容量
    static final int MAXIMUM_CAPACITY = 1 << 30;
    //默认填充因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    //当链表的长度大于这个值将转换为红黑树
    static final int TREEIFY_THRESHOLD = 8;
    //当红黑树的大小小于这个值转化为链表
    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;
    //map中元素的个数
    transient int size;
    //每次对map结构进行修改,进行计数
    transient int modCount;
    //(容量 * 加载因子),当map中存放的元素个数大于等于这个值会进行扩容
    int threshold;
    //加载因子
    final float loadFactor;

hash()

jdk1.8中

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

jdk1.7中

static int hash(int h) {
            h ^= (h >>> 20) ^ (h >>> 12);
            return h ^ (h >>> 7) ^ (h >>> 4);
}

h >>>16为主要是为了让key的hashcode的高位也能参与运算,减少hash冲突的概率。hash方法中使用的都是位运算,因为位运算的效率比较高,所以table数组的大小总是2的次幂。

hash函数也被称为扰动函数,jdk1.7中扰动了四次性能更低,所以在1.8中进行了改进。

Node节点类

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;
    }
}

树节点类

static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
    TreeNode<K,V> parent;  // red-black tree links
    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;
        }
    }

四种构造方法

//指定容量、加载因子的构造方式
//传入容量、加载因子,首先会对容量和加载因子进行校验
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()

final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
    int s = m.size();
    if (s > 0) {
        if (table == null) { // pre-size
            float ft = ((float)s / loadFactor) + 1.0F;
            int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                     (int)ft : MAXIMUM_CAPACITY);
            if (t > threshold)
                threshold = tableSizeFor(t);
        }
        else if (s > threshold)
            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);
        }
    }
}

put()

HashMap提供给我们调用的是put()方法,但底层put方法其实是调用了putVal方法。

put的过程:

  • 通过hash值和数组长度计算该key对应的下标位置
  • 判断该位置是否已经有元素,如果没有,直接插入
  • 如果有元素,先比较这个节点已经有的元素的hash和key是否和put进去的key和hash相等,如果相等直接覆盖
  • 如果不相等,表明有hash冲突,就需要往下便利了,先判断当前节点是否为树节点,如果是树节点就用putTreeVal的方法去添加元素
  • 如果不是树节点,往下遍历链表,如果有hash和key都相等的直接覆盖
  • 如果没有,将该元素插入链表尾部(在jdk1.7中采用头插法插入)
  • 修改modCount记录map结构修改次数
  • 判断是否需要扩容
public V put(K key, V value) {
    //调用putVal方法添加元素
    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;
    //如果tab长度为0未初始化,进行扩容
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
    //如果通过hash与数组长度计算后得到的数组下标对应的元素为null,表示该位置还没有值,直接插入
        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 = p;
            //如果不相等,需要使用拉链法往后插入节点了,先判断首节点是否为红黑树节点,如果是就调用红黑树添加节点的方法putTreeVal
            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);
                        //判断是否大于阈值8将链表转换为红黑树,使用treeifBin方法,还会判断当前数组长度是否大于64
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    // 如果在遍历链表的过程中有hash和key都相等的节点,直接break循环
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            //将value值替换
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
    //记录map结构修改次数
        ++modCount;
    //判断当前map元数个数是否大于threshold,大于就进行扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

get()

和put方法一样map提供给我们的是get()方法,但底层get会去调用getNode方法

get的过程

  • 通过hash计算key对应的数组下标位置
  • 比较hash和key是否都相同,相同返回
  • 不相同,判断该节点是否还有后驱节点,如果有判断是否为树
  • 如果是树,调用getTreeNode方法
  • 如果不是遍历链表寻找key和hash相等的值,没有返回null
public V get(Object key) {
    Node<K,V> e;
    //如果没有这个key直接返回null
    return (e = getNode(hash(key), key)) == null ? null : e.value;
}

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) {
            //先判断通过hash计算后得到下标位置对应的节点是否hash和key都相等,相等直接返回
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            //如果第一个节点不是我们要找的,并且这个节点的next节点不为空,表示是一个链表
            if ((e = first.next) != null) {
                //判断是否为树,如果为树,调用getTreeNode方法
                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()

resize方法会对所有元素进行rehash操作,要遍历整个表,是非常耗时的,我们要避免频繁的resize。

在jdk1.8之后每次扩容斌不需要重新计算hash值,因为每次扩容都是翻倍,每次扩容后节点要么在原来的位置,要么在原位置+旧容量的位置。扩容之后的数组长度其实就是多了一个bit位。

在这里插入图片描述

从图中可以看出key1和key2在扩容前16和扩容后32计算出来的位置有所不同,key1还是在原位置,key2到了新的位置。

下面对源代码进行分析

final Node<K,V>[] resize() {
    Node<K,V>[] oldTab = table;
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    int oldThr = threshold;
    int newCap, newThr = 0;
    if (oldCap > 0) {
        //超过最大值无法扩容,只能hash冲突了
        if (oldCap >= MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        //当原数组的容量扩容2倍后小于最大容量且原数组容量大于初始化默认容量的时候,更新新的newThr等于oldThr的两倍
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                 oldCap >= DEFAULT_INITIAL_CAPACITY)
            newThr = oldThr << 1; // double threshold
    }
    else if (oldThr > 0) // initial capacity was placed in threshold
        newCap = oldThr;
    else {               // zero initial threshold signifies using defaults
        newCap = DEFAULT_INITIAL_CAPACITY;
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
    //计算新的threshold值
    if (newThr == 0) {
        float ft = (float)newCap * loadFactor;
        newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                  (int)ft : Integer.MAX_VALUE);
    }
    //将新的扩容阈值赋值给成员变量threshold
    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) {
            //用节点e来存储当前节点
            Node<K,V> e;
            //如果遍历到的当前节点不为空,则置为空,方便GC,而这个节点的值已经被保存到节点e中了
            if ((e = oldTab[j]) != null) {
                oldTab[j] = null;
                //如果没有下一个节点,不是链表,直接放入新的数组
                if (e.next == null)
                    newTab[e.hash & (newCap - 1)] = e;
                //如果有next节点,则判断该节点是不是树节点
                else if (e instanceof TreeNode)
                    //如果是树节点,将树进行拆分,因为需要rehash
                    ((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;
                    //记录链表中当前节点的next节点
                    Node<K,V> next;
                    do {
                        next = e.next;
                        //计算高位为0则旧节点在新数组的位置就是原位置,如上面一张计算位置的图
                        if ((e.hash & oldCap) == 0) {
                            if (loTail == null)
                                loHead = e;
                            else
                                loTail.next = e;
                            loTail = e;
                        }
                        //不为0,就是原位置加旧数组的容量
                        else {
                            if (hiTail == null)
                                hiHead = e;
                            else
                                hiTail.next = e;
                            hiTail = e;
                        }
                        //next为空,链表遍历完毕,结束循环
                    } while ((e = next) != null);
                    if (loTail != null) {
                        loTail.next = null;
                        //原位置
                        newTab[j] = loHead;
                    }
                    if (hiTail != null) {
                        hiTail.next = null;
                        //原位置 + 旧容量
                        newTab[j + oldCap] = hiHead;
                    }
                }
            }0-p
        }
    }
    return newTab;
}
(e = next) != null);
                    if (loTail != null) {
                        loTail.next = null;
                        //原位置
                        newTab[j] = loHead;
                    }
                    if (hiTail != null) {
                        hiTail.next = null;
                        //原位置 + 旧容量
                        newTab[j + oldCap] = hiHead;
                    }
                }
            }0-p
        }
    }
    return newTab;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小C卷Java

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值