Java基础集合-HashMap1.8

HashMap介绍

HashMap是基于哈希表的Map接口实现,它提供了Map的所有操作,并且允许键值为null的键值对(最多只能有一个键值对的键为null,键的hash值会由0代替)。HashMap大致和HashTable相同,只是HashMap是非同步的,以及允许为null的键值。

需要注意的是JDK1.7和JDK1.8有着完全不同的HashMap实现,下面只对JDK1,8的HashMap展开分析。

HashMap实例的性能取决于两个参数:

  • 初始容量:哈希表创建时的桶数
  • 负载因子:哈希表扩容的度量

不能将初始容量设置的过高或过低,不然会影响迭代性能,集合的迭代时间与HashMap实例的容量(存储桶数)及其大小(键-值对数)成正比。

当哈希表中的键值对数目超过负载因子和当前容量的乘积时,哈希表将被重新哈希,其内部数据结构将被重建。

HashMap桶中链表长度为8时转红黑树:在源码中作者有根据泊松分布给出桶长度的频率表,由频率表可以看出,当负载因子为0.75时,桶中元素达到8个的概率非常小。

属性常量

/**
 * The default initial capacity - MUST be a power of two.
 */
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

/**
 * The maximum capacity, used if a higher value is implicitly specified
 * by either of the constructors with arguments.
 * MUST be a power of two <= 1<<30.
 * 最大容量,为什么int的最大值2^31-1呢?和扩容机制有关,保证容量为2的幂
 */
static final int MAXIMUM_CAPACITY = 1 << 30;

/**
 * The load factor used when none specified in constructor.
 * 默认扩容负载因子
 */
static final float DEFAULT_LOAD_FACTOR = 0.75f;

/**
 * The bin count threshold for using a tree rather than list for a
 * bin.  Bins are converted to trees when adding an element to a
 * bin with at least this many nodes. The value must be greater
 * than 2 and should be at least 8 to mesh with assumptions in
 * tree removal about conversion back to plain bins upon
 * shrinkage.
 * 树化阈值
 */
static final int TREEIFY_THRESHOLD = 8;

/**
 * The bin count threshold for untreeifying a (split) bin during a
 * resize operation. Should be less than TREEIFY_THRESHOLD, and at
 * most 6 to mesh with shrinkage detection under removal.
 * 链化阈值
 */
static final int UNTREEIFY_THRESHOLD = 6;

/**
 * The smallest table capacity for which bins may be treeified.
 * (Otherwise the table is resized if too many nodes in a bin.)
 * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
 * between resizing and treeification thresholds.
 * TREEIFY_THRESHOLD达到8也不一定树化,必须保证总容量达到64
 */
static final int MIN_TREEIFY_CAPACITY = 64;

实例属性

/**
 * 哈希表,懒初始化(在第一次存入元素的时候),自动调整大小,长度为2的倍数
 */
transient Node<K,V>[] table;

/**
 * Holds cached entrySet(). Note that AbstractMap fields are used
 * for keySet() and values().
 */
transient Set<Map.Entry<K,V>> entrySet;

/**
 * 元素个数
 */
transient int size;

/**
 * 迭代时的并发修改次数
 */
transient int modCount;

/**
 * 当前容量与负载因子的乘积,表示下次扩容的元素个数阈值
 */
// (The javadoc description is true upon serialization.
// Additionally, if the table array has not been allocated, this
// field holds the initial array capacity, or zero signifying
// DEFAULT_INITIAL_CAPACITY.)
int threshold;

/**
 * 负载因子,默认0.75
 * @serial
 */
final float loadFactor;

构造函数

通过构造函数可以指定初始容量和负载因子:

public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

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(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

public V put(K key,V value)

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

首先会根据key获取hash值:

  • HashMap仅允许一个元素的键为null,其hash用0代替
  • 获取key的hashCode值,高16位和低16位与运算,获得16位的有效数值
static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict)

真正存入元素的方法:

/**
 * Implements Map.put and related methods
 *
 * @param hash hash for key
 * @param key the key
 * @param value the value to put
 * @param onlyIfAbsent if true, don't change existing value
 * @param evict if false, the table is in creation mode.
 * @return previous value, or null if none
 */
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    // 判断hash表是否为空
    if ((tab = table) == null || (n = tab.length) == 0)
        // 初始化hash表或重新构建
        n = (tab = resize()).length;
    // 根据key的hash计算所在桶的索引
    // p为该桶的头结点
    if ((p = tab[i = (n - 1) & hash]) == null)
        // 该桶为空,直接放入桶数组位置
        tab[i] = newNode(hash, key, value, null);
    // 桶不为空
    else {
        Node<K,V> e; K k;
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            // 存入key与头结点key相同,覆盖
            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);
                    // 判断链表长度,此时binCount为7,则链长为8
                    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))))
                    // 存入key与该结点key相同,覆盖
                    break;
                // 指针移动到下一个链节点
                p = e;
            }
        }
        // e不为null,表示存入的key已经在
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            // 会覆盖值
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            // 返回旧值
            return oldValue;
        }
    }
    ++modCount;
    // 更新元素个数,重哈希
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}
resize()
  • 初始化哈希表
  • 或按照旧表容量的2倍扩容并重新分配元素
/**
 * 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;
    // 扩容阈值,默认为0
    int oldThr = threshold;
    int newCap, newThr = 0;
    if (oldCap > 0) {
        if (oldCap >= MAXIMUM_CAPACITY) {
            // hash数组的达到上限
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
   		// 新哈希表容量2倍
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                 oldCap >= DEFAULT_INITIAL_CAPACITY)
            // 扩容阈值也2倍
            newThr = oldThr << 1; // double threshold
    }
    // 通过构造指定了初始容量
    else if (oldThr > 0) // initial capacity was placed in threshold
        newCap = oldThr;
    else {               // zero initial threshold signifies using defaults
        // 16
        newCap = DEFAULT_INITIAL_CAPACITY;
        // 12
        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) {
                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;
}
public V get(Object key)
(e.hash & oldCap) == 0?

将重新分配的元素key hash值和旧哈希表容量相与是什么意思呢?

假设oldCap为16,则newCap=32:

  • newCap(b)-1 = 11111

  • oldCap(b) = 10000

  • node1.hash = 1010010

  • node2.hash = 1000010

相当于两个hash的第五位和oldCap的第五位相与,node1为1,node2为0。

  • 相与为0,则在新表中桶索引不变,00010
  • 相与为1,则在新表中索引是10010,相比在旧表中的桶索引左移一位,增加16

综上:HashMap扩容后,元素所在的桶索引要么不变,要么变为再移动二次幂的位置

public V get(Object key)

首先根据key计算hash值

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)

真正获取元素的方法:

/**
 * Implements Map.get and related methods
 *
 * @param hash hash for key
 * @param key the key
 * @return the node, or null if none
 */
final Node<K,V> getNode(int hash, Object key) {
    Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
    // 根据key的hash值获取桶索引
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (first = tab[(n - 1) & hash]) != null) {
        if (first.hash == hash && // always check first node
            ((k = first.key) == key || (key != null && key.equals(k))))
            // 真巧,目标元素就是桶的头结点
            return first;
        if ((e = first.next) != null) {
            // 如果这个桶是树结构,则要专门通过树的方式获取节点
            if (first instanceof TreeNode)
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            // 链表结构,循环遍历匹配key就行了
            do {
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}

HashMap 1.7和1.8比较

  • 数据结构
    • JDK1.7:数组+链表
    • JDK1.8:数组+链表+红黑树
  • 插入方法
    • JDK1.7:头插法。存在循环链表
    • JDK1.8:尾插法。因为采用尾插法,解决了循环链表问题
  • 扩容机制
    • JDK1.7:hash&需要扩容的二进制数,所以扩容必须是2的幂
    • JDK1.8:扩容前所在桶索引&扩容后的容量
      • 0:当前桶
      • 1:扩容前所在桶索引+扩容后的容量(相当于所在桶索引变为之前的2倍)
  • 线程安全问题:
    • JDK1.7:因为采用头插法,存在环形链表的问题
    • JDK1.8:元素并发插入到同一位置,造成数据覆盖

为什么使用红黑树而不是二叉树?

二叉查找树在特殊情况下会导致一条分支过深,遍历查找变慢

而红黑树插入后需要通过旋转、变色来保持树的平衡

红黑树特性
  • 每个节点非红即黑
  • 根节点总是黑色的
  • 如果节点是红色的,则它的子节点必须是黑色的(反之不一定)
  • 每个叶子节点都是黑色的空节点(NIL节点)
  • 从根节点到叶节点或空子节点的每条路径,必须包含相同数目的黑色节点(即相同的黑色高度)

HashMap为啥不是线程安全?

  • 操作HashMap的方法不是同步的,如:put(),resize()等
  • 多个线程并发执行put操作时,如果hash相同,则会造成冲突

为什么HashMap扩容是2的幂?

  • 2的幂的值n只有最高位为1,其余位全部为0
  • hash数组索引是0~(n-1),(n-1)的每一个都为1
  • 这样参与hash运算的key的hash值每一位都能&1
  • 降低哈希冲突

为什么采用数据+链表

  • 数组用来根据hash运算确定桶的位置
  • 链表用来解决hash冲突
解决hash冲突的方案
  • 开放地址法
  • 链地址法
  • 再哈希法
  • 公共溢出区域法
哈希数组可用LinkList代替吗

源码中的hash数组:

Entry[] table = new Entry[capacity];

所以可以使用List。但为什么不使用LinkList呢?

  • 采用数组结构,扩容机制可以自己定义,HashMap中数组扩容刚好是2的幂,在做hash运算时效率高
  • 而ArrayList有自己的扩容机制,1.5倍扩容

环型链表

发生场景:JDK1.7中在执行transfer扩容转移元素时

哈希表如何解决冲突?

image-20210107091712006

为什么HashMap键值都允许为空、线程不安全、不保证有序、存储位置会变化?

image-20210107091938762

为什么HashMap中String、Integer这样的包装类适合作为key

image-20210107092050751

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值