Java 集合深入理解 (十二) :HashMap之扩容 数据迁移

Java 集合深入理解 (十一) :哈希表之HashMap原理

目录

Java 集合深入理解 (十一) :哈希表之HashMap原理

前言

hashmap中扩容方法(resize())

扩容调用的时间段

源码分析

putIfAbsent方法

get(Object key)方法

remove(Object key) 方法

keySet()方法

HashIterator 迭代器

总结


前言

 上一篇我做了哈希表之HashMap原理的分析包括,整个属性 及构造方法  put方法的整体分析,也有了个大概,这篇文章进一步解析扩容 数据迁移  删除的原理分析

hashmap中扩容方法(resize())

扩容调用的时间段

  • put方法中,初始化hashmap  
  • size大于所设置threshold(阈值)时,并且插入链表那个值不为空时
  if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
  • 以及jdk1.8后提供的computeIfAbsent 和putIfAbsent 方法中

源码分析

源码分析前有几个问题,hashmap是怎么扩容的,扩容过后数据是怎么在重新分配数据,一次性扩容多大的数组 ,让我们带着这些问题去看看

对链表进行扩容元素拆分

测试数据

public static void main(String[] args) {
		 List<String> list = new ArrayList<>();
		    list.add("ff");
		    list.add("ssd");
		    list.add("c");
		    list.add("e4wewre");
		    list.add("f");
		    list.add("s");
		    list.add("vfgx6");
		    list.add("gfxcrt");
		    list.add("alvpo");
		    list.add("vsdfbh");
		    list.add("bsdfnhj");
		    list.add("zucxio");
		    list.add("iu8xce");
		    list.add("yhjghk");
		    list.add("plwop");
		    list.add("r");
		    for (String key : list) {
		        int hash = key.hashCode() ^ (key.hashCode() >>> 16);
		        System.out.println("字符串:" + key + " \tIdx(16):" + ((16 - 1) & hash) + " \tBit值:" + Integer.toBinaryString(hash) + " - " + Integer.toBinaryString(hash & 16) + " \t\tIdx(32):" + ((
		        Integer.toBinaryString(key.hashCode()) +" "+ Integer.toBinaryString(hash) + " " + Integer.toBinaryString((32 - 1) & hash))));
		    }
	}


字符串:ff 	Idx(16):0 	Bit值:110011000000 - 0 		Idx(32):110011000000 110011000000 0
字符串:ssd 	Idx(16):5 	Bit值:11011111000000101 - 0 		Idx(32):11011111000000100 11011111000000101 101
字符串:c 	Idx(16):3 	Bit值:1100011 - 0 		Idx(32):1100011 1100011 11
字符串:e4wewre 	Idx(16):3 	Bit值:111110010011100011101000000011 - 0 		Idx(32):111110010011100000010001001101 111110010011100011101000000011 11
字符串:f 	Idx(16):6 	Bit值:1100110 - 0 		Idx(32):1100110 1100110 110
字符串:s 	Idx(16):3 	Bit值:1110011 - 10000 		Idx(32):1110011 1110011 10011
字符串:vfgx6 	Idx(16):11 	Bit值:110101011101100001000011011 - 10000 		Idx(32):110101011101100010010110101 110101011101100001000011011 11011
字符串:gfxcrt 	Idx(16):4 	Bit值:10110101100110000010011001010100 - 10000 		Idx(32):10110101100110001001001111001100 10110101100110000010011001010100 10100
字符串:alvpo 	Idx(16):3 	Bit值:101100010011100110101100011 - 0 		Idx(32):101100010011100100011101010 101100010011100110101100011 11
字符串:vsdfbh 	Idx(16):10 	Bit值:11001111110111111010011101011010 - 10000 		Idx(32):11001111110111110110100010000101 11001111110111111010011101011010 11010
字符串:bsdfnhj 	Idx(16):12 	Bit值:1010000100010011111001101100 - 0 		Idx(32):1010000100010011010001111101 1010000100010011111001101100 1100
字符串:zucxio 	Idx(16):8 	Bit值:11010110110011100001110011011000 - 10000 		Idx(32):11010110110011101100101000010110 11010110110011100001110011011000 11000
字符串:iu8xce 	Idx(16):6 	Bit值:10111001101110000110001101110110 - 10000 		Idx(32):10111001101110001101101011001110 10111001101110000110001101110110 10110
字符串:yhjghk 	Idx(16):10 	Bit值:11010100011001010111101011101010 - 0 		Idx(32):11010100011001011010111010001111 11010100011001010111101011101010 1010
字符串:plwop 	Idx(16):1 	Bit值:110010111010010101101000001 - 0 		Idx(32):110010111010010110100011100 110010111010010101101000001 1
字符串:r 	Idx(16):2 	Bit值:1110010 - 10000 		Idx(32):1110010 1110010 10010

对链表进行拆分

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

 通过源码和图进行分析知道了整个扩容拆分就来自于 该段代码,将链表进行重分组装

数据量大了之后,明显扩容相当消耗性能

最后扩容过后的数组应该为原数组的两倍

putIfAbsent方法

从源码上看和 put方法是一样的  ,但 onlyIfAbsent 设置为true  也就是key对应的value已经存在,就返回存在的value,不进行替换。  在jdk1.8中,作者的用意是用来做缓存的api操作

 @Override
    public V putIfAbsent(K key, V value) {
        return putVal(hash(key), key, value, true, true);
    }

get(Object key)方法

 /**
*返回指定键映射到的值,或者{@code null},如果此映射不包含键的映射。
*
*<p>更正式地说,如果此映射包含来自键的映射{@code k}到值{@code v}这样{@code(key==null?k==空:
*equals(k))},则此方法返回{@codev};否则它返回{@code null}(最多可以有一个这样的映射。)
*
*<p>返回值{@code null}不一定</i>指示映射不包含密钥的映射;这也是映射可能显式地将键映射到{@code null}。
*{@link#containsKey containsKey}操作可用于
*区分这两种情况。
*
*@see#put(object,object)
*/
    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

这里get方法还是比较简单的 主要就是找到对应的 object类,进行返回数据;始终检查第一个节点,第一个进行遍历进行查找

remove(Object key) 方法

  /**
     * 从此映射中删除指定键的映射(如果存在)。
     *
     * @param  要从映射中删除其映射的键
     * @return 与<tt>键相关的上一个值,或
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }

分析 removeNode方法

   /**
     * 实现Map.remove和相关方法 是final的
     *
     * @param hash的key值
     * @param key the key
     * @param value要匹配的值if matchValue,else忽略
     * @param matchValue if true仅在值相等时删除
     * @param 如果为false,则在删除时不移动其他节点
     * @return 节点,如果没有则为null
     */
    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;
        // 获取n为table长度,index为hash后的位置
        // 如果当前table已经初始化,且index位置上的元素不为空,则进入if判断,准备查找需要删除的元素
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (p = tab[index = (n - 1) & hash]) != null) {
            Node<K,V> node = null, e; K k; V v;
            //如果当前index位置上第一个元素则是需要被删除的元素,则将node指定为p,开始删除
            //如果不是则进入else循环开始查找
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
            //如果当前index位置上下一个元素不为空,则判断类型进行查找
            else if ((e = p.next) != null) {
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
                else {
                     //如果当前index位置为链表,则循环向后查找
                    do {
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
            //如果node不为null,则代表查找到key值对应的元素
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
                //如果被查找到的node类型为树类型,则调用树的删除方法
                if (node instanceof TreeNode)
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                else if (node == p)
                    tab[index] = node.next;
                else
                    p.next = node.next;
                //将操作数加一
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

这里对remove方法进行备注展示,这些都是比较简单的循环查找

keySet()方法

keyset方法用于获取到 所有的key 集合 ,查看源码put中没有添加 到set集合中,并且支持迭代器元素删除,这一一的疑问通过找到源码去看

  /**
     * 返回此映射中包含的键的{@link Set}视图。
     * 集合由映射支持,因此对映射的更改
     * 反映在场景中,反之亦然。如果地图被修改
     * 当集合上的迭代正在进行时(除了通过
     * 迭代器自己的<tt>remove</tt>操作)的结果
     * 迭代未定义。支持元素移除,
     * 从地图上删除相应的映射, 
     * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
     * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
     * operations.  It does not support the <tt>add</tt> or <tt>addAll</tt>
     * operations.
     *
     * @return 此地图中包含的键的集合视图
     */
    public Set<K> keySet() {
        Set<K> ks = keySet;
        if (ks == null) {
            ks = new KeySet();
            keySet = ks;
        }
        return ks;
    }


  final class KeySet extends AbstractSet<K> {
        public final int size()                 { return size; }
        public final void clear()               { HashMap.this.clear(); }
        public final Iterator<K> iterator()     { return new KeyIterator(); }
        public final boolean contains(Object o) { return containsKey(o); }
        public final boolean remove(Object key) {
            return removeNode(hash(key), key, null, false, true) != null;
        }
        public final Spliterator<K> spliterator() {
            return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);
        }
        public final void forEach(Consumer<? super K> 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.key);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }
    }
  • 通过 调用KeySet 方法 ,创建keyset对象给我们,这个keyset对象,是继承自 abstractset的,它会实现  一些set常用的方法
  • 主要是通过调用hashmap的公共方法进行实现
  • 在源码中还给我们实现了KeyIterator迭代器,KeyIterator 是继承HashIterator 迭代器, 后面我们继续讨论迭代器 

HashIterator 迭代器

从源码中可以看到 所有的迭代器,都来自于HashIterator 迭代器 ,并只做了把next方法重构,重点研究HashIterator

 final class KeyIterator extends HashIterator
        implements Iterator<K> {
        public final K next() { return nextNode().key; }
    }

    final class ValueIterator extends HashIterator
        implements Iterator<V> {
        public final V next() { return nextNode().value; }
    }

    final class EntryIterator extends HashIterator
        implements Iterator<Map.Entry<K,V>> {
        public final Map.Entry<K,V> next() { return nextNode(); }
    }

  abstract class HashIterator {
        Node<K,V> next;        // 要返回的下一个条目
        Node<K,V> current;     // 当前条目
        int expectedModCount;  // 对于快速故障
        int index;             // 当前插槽

        HashIterator() {
            expectedModCount = modCount;
            Node<K,V>[] t = table;
            current = next = null;
            index = 0;
            if (t != null && size > 0) { // 提前到第一个入口
                do {} while (index < t.length && (next = t[index++]) == null);
            }
        }

        public final boolean hasNext() {
            return next != null;
        }

        final Node<K,V> nextNode() {
            Node<K,V>[] t;
            Node<K,V> e = next;
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            if (e == null)
                throw new NoSuchElementException();
            if ((next = (current = e).next) == null && (t = table) != null) {
                do {} while (index < t.length && (next = t[index++]) == null);
            }
            return e;
        }

        public final void remove() {
            Node<K,V> p = current;
            if (p == null)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            current = null;
            K key = p.key;
            removeNode(hash(key), key, null, false, false);
            expectedModCount = modCount;
        }
    }

由图基本了解了整个思路是怎么样的跳转

总结

整个hashmap扩容机制,也遍历等方法 ,迭代器在我们日常应用中应用很广泛,希望这篇文章对你理解hashmap有整体的一个了解

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

踩踩踩从踩

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

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

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

打赏作者

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

抵扣说明:

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

余额充值