美文网首页
HashMap源码分析

HashMap源码分析

作者: NoBugException | 来源:发表于2019-12-24 19:13 被阅读0次

    数据结构是程序的重要组成部分,选择好的数据结构可以让程序更加高效。对于数据的操作,无非就是增、删、改、查,下面将讲解为什么使用HashMap以及它的原理。

    起初,存储数据最简单的数据结构是数组

    【数组】

    一片物理上连续的大小确定的存储空间。如:

    int[] a = new int[10];
    

    这里的数组 指一维数组,二维数组不做考虑。

    我在网上截了一张一维数组的图片,如图:

    图片.png
    数据的元素都是有角标的,如图所示,数组的大小是n,元素角标从0开始,a[0]=a1,a[1]=a2,a[2]=a3,a[3]=a4,a[4]=a5,a[5]=a6,a[6]=a7...等等。

    数组元素的操作有四种,分别是:增、删、改、查。

    查找: 查询比较简单,假如在一个长度为n的数组里查找数值为m的数,那么只能根据数组的角标顺序查找,它的时间复杂度为n,简称O(n)。
    增加、删除: 由于数组的大小不变(物理上连续的存储空间),所以数据无法做到增加和删除操作。
    修改: 修改就是更新某角标的数据,直接赋值即可,如:

    a[i] = m;
    

    为了解决数组不可增加、删除的问题,引入了顺序表

    【顺序表】

    顺序表就是我们常用的ArrayList,它是物理上连续、逻辑上连续、大小可以动态增加的数据结构。

    ArrayList弥补了数组不能添加和删除元素的缺陷。

    有关ArrayList增加和删除元素的代码如下:

        ArrayList<String> list = new ArrayList<>();
        //添加一个元素
        list.add("张三");
        //在角标为0的位置上插入一个元素
        list.add(0, "李四");
        //移除一个元素
        list.remove("张三");
        //在指定位置上移除一个元素
        list.remove(0);
    

    我们来分析一下源码:

    /**
     * Appends the specified element to the end of this list.
     *
     * @param e element to be appended to this list
     * @return <tt>true</tt> (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
    

    它的意思是,在顺序表的末尾增添一个新的元素,elementData是一个Object数组

    transient Object[] elementData;
    

    将新增的元素赋值到elementData[size++] 中

    elementData[size++] = e;
    

    但是,问题来了,elementData的长度是size,那么以上的赋值操作不是数组越界了吗?我们发现,在赋值之前,还有一句代码:

    ensureCapacityInternal(size + 1);  // Increments modCount!!
    
    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }
    
        ensureExplicitCapacity(minCapacity);
    }
    
    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;
    
        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
    
    /**
     * Increases the capacity to ensure that it can hold at least the
     * number of elements specified by the minimum capacity argument.
     *
     * @param minCapacity the desired minimum capacity
     */
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
    

    最终走到了grow方法中,minCapacity为size+1,核心代码如下:

    elementData = Arrays.copyOf(elementData, newCapacity);
    

    它的意思是,使用Arrays.copyOf重新创建一个新的数组,新数组的大小是newCapacity,将原来数组elementData中的所有源码赋值到新的数组中。(重点)

    我们再来分析一下以下源码:

    /**
     * Inserts the specified element at the specified position in this
     * list. Shifts the element currently at that position (if any) and
     * any subsequent elements to the right (adds one to their indices).
     *
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public void add(int index, E element) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }
    

    其核心代码是:

    System.arraycopy(elementData, index, elementData, index + 1, size - index);
    

    和上面提到的Arrays.copyOf作用是一样的,它们的却别是:

    Arrays.copyOf是新建一个大小为size +1的数组,并将原来的数组的数据复制到新的数组中;
    System.arraycopy是新建一个大小为size+1的数组,将原有数组的[0~index]范围中的元素拷贝到新数组的[0~index]位置上,将原有数组剩余的元素全部拷贝到新数组的[index+1~size+1]位置上。
    

    remove方法的源码就不说了,和add一样,使用了Arrays.copyOfSystem.arraycopy这两个方法。

    所以,我们得出的结论是,顺序表(ArrayList)本质上就是一个数组(int[]),它和数组一样,都是有角标的,所以查找的速度是非常快的,但是,缺点是:速度特别慢。

    那么,有没有好的数据结构解决这个问题呢?

    有的,链表可以解决查找速度慢的问题。

    【链表】

    链表就是我们常用的LinkedList,它是物理上不连续、逻辑上连续、可以动态添加和删除节点的数据结构。

    链表分为:单链表、双链表、循环单链表,这里只说明单链表。

    我在网上截了一张图,如下:

    图片.png

    链表的元素由若干个节点组成,每个节点由数据和next组成。d1、d2、d3就是链表的数据,next指向下一个节点的地址。

    链表在物理上不连续,但是在逻辑上是连续的,节点中的next将若干个节点在逻辑上串连在一起。

    链表增加和删除节点的代码如下:

        LinkedList<String> list = new LinkedList<>();
        //添加一个元素,默认在末尾添加一个元素
        list.add("张三");
        //在末尾添加一个元素
        list.addLast("张三");
        //在链表首部添加一个元素
        list.addFirst("张三");
        //在指定位置添加一个元素
        list.add(0, "张三");
        //移除某元素
        list.remove("张三");
        //删除一个元素,默认删除首部元素
        list.remove();
        //删除首部元素
        list.removeFirst();
        //删除尾部元素
        list.removeLast();
        //删除指定位置的元素
        list.remove(0);
    

    开始分析源码:

    /**
     * Inserts the specified element at the specified position in this list.
     * Shifts the element currently at that position (if any) and any
     * subsequent elements to the right (adds one to their indices).
     *
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public void add(int index, E element) {
        checkPositionIndex(index);
    
        if (index == size)
            linkLast(element);
        else
            linkBefore(element, node(index));
    }
    

    add(int index, E element)在链表的指定位置添加一个元素,如果index正好等于链表的长度,那么就直接在链表的尾部添加一个元素,不需要消耗查找所需需要的时间,如果index不等于链表的长度,那么执行以下代码:

    linkBefore(element, node(index));
    

    下面来了重点知识,linkBefore方法的作用是将element插入到index位置上,在插入元素之前必须先找到index对应的节点,也就是linkBefore方法的第二个参数引用的方法:

    /**
     * Returns the (non-null) Node at the specified element index.
     */
    Node<E> node(int index) {
        // assert isElementIndex(index);
    
        if (index < (size >> 1)) {
            Node<E> x = first;
            for (int i = 0; i < index; i++)
                x = x.next;
            return x;
        } else {
            Node<E> x = last;
            for (int i = size - 1; i > index; i--)
                x = x.prev;
            return x;
        }
    }
    

    Node表示节点,通过for循环,从第一个元素或者最后一个元素开始查找,直到遍历到第index个节点为止。这就是链表的缺点,查询操作比较慢。

    最终,根据等待插入的数据和index位置的节点开始插入操作。

    /**
     * Inserts element e before non-null Node succ.
     */
    void linkBefore(E e, Node<E> succ) {
        // assert succ != null;
        final Node<E> pred = succ.prev;
        final Node<E> newNode = new Node<>(pred, e, succ);
        succ.prev = newNode;
        if (pred == null)
            first = newNode;
        else
            pred.next = newNode;
        size++;
        modCount++;
    }
    

    在这里,可以得出结论是,链表插入和删除数据不需要移动或拷贝元素,直接next 即可完成增加和删除操作,所以速度是比较快的,但是当在指定位置插入节点时,必须找到当前位置的节点,这个查询操作是非常的慢的,这是链表最主要的缺点了。

    为了解决链表查找速度慢的问题,我们必须找到一个既查找速度快,又添加删除速度快的数据结构。

    首先,整理一下顺序表和链表的优缺点,如表:

    顺序表 链表
    优点 查找快 删除增加元素快
    缺点 增删慢 查找慢

    那么,有没有一种数据结构可以结合两者的优点呢?

    答案是有的,这就是我们常说的哈希表

    我在网上截了一张图,如下:

    图片.png

    哈希表是由数组+链表组成的混合结构,在图中纵向的0~15表示一个数组,每个数组的下标都可以含有一个链表。

    当使用put方法添加元素时,首先需计算出数组的索引,再将元素插入到当前数组索引对应链表的某个位置。实际上,往往插入元素的次数比较频繁,在索引为12的位置上插入过多的元素,每次都要从头遍历当前索引所对应链表,如果key相同,则替换掉原来的value值,否则直接在链表的末尾添加元素。像这种,重复的在某索引下插入元素叫做碰撞。很明显,如果碰撞次数太多,会大大的影响hashmap的性能。那么,怎么才能减少碰撞的次数呢?请继续往下看。

    本文讲解HashMap的大方向主要有以下几点:

    • 构造方法
    • 插入元素
    • 获取元素
    • 遍历
    (1)构造方法

    【方法一】

    /**
     * Constructs an empty <tt>HashMap</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     */
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }
    

    在这个方法中,DEFAULT_LOAD_FACTOR负载系数,源码中的定义如下:

    /**
     * The load factor used when none specified in constructor.
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    

    负载系数默认为0.75,这个参数和HashMap的扩容有关。

    另外,HashMap是有容量的,此时HashMap的默认容量是16,源码中的定义如下:

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

    【方法二】

    /**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and the default load factor (0.75).
     *
     * @param  initialCapacity the initial capacity.
     * @throws IllegalArgumentException if the initial capacity is negative.
     */
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
    

    这个构造方法容量可以自定义,至于负载系数采用默认值0.75。

    【方法三】

    /**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and load factor.
     *
     * @param  initialCapacity the initial capacity
     * @param  loadFactor      the load factor
     * @throws IllegalArgumentException if the initial capacity is negative
     *         or the load factor is nonpositive
     */
    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);
    }
    

    这个方法可以任意指定HashMap的容量以及负载系数。容量的大小不能大于MAXIMUM_CAPACITY,有关MAXIMUM_CAPACITY源码中的定义代码是:

    /**
     * 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.
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;
    

    转成十进制是:

    static final int MAXIMUM_CAPACITY = 1073741824;
    

    另外,这个方法中的tableSizeFor方法是计算当前容量的阈值,即最大容量,最大容量总是等于2的n次幂,假如HashMap的容量是9,那么数组的大小是16,2的4次幂。计算数组大小的源码如下:

    /**
     * Returns a power of two size for the given target capacity.
     */
    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;
    }
    

    【方法四】

    /**
     * Constructs a new <tt>HashMap</tt> with the same mappings as the
     * specified <tt>Map</tt>.  The <tt>HashMap</tt> is created with
     * default load factor (0.75) and an initial capacity sufficient to
     * hold the mappings in the specified <tt>Map</tt>.
     *
     * @param   m the map whose mappings are to be placed in this map
     * @throws  NullPointerException if the specified map is null
     */
    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }
    

    这个方法的形参就是HashMap集合,想都不用想,肯定会遍历旧集合,并一个一个添加到新的集合中。putMapEntries方法的源码如下:

    /**
     * Implements Map.putAll and Map constructor
     *
     * @param m the map
     * @param evict false when initially constructing this map, else
     * true (relayed to method afterNodeInsertion).
     */
    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);
            }
        }
    }
    

    其中putVal方法就是插入元素。

    (2)插入元素

    当需要添加元素时,代码实现如下:

        HashMap<String, String> hashMap = new HashMap<>();
        //添加一个元素
        hashMap.put("key", "value");
    

    那么,put方法的原理是什么呢?想要知道这个答案,必须研究下源码了。

    /**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <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 put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
    
    /**
     * 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;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        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))))
                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);
                        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;
                    p = e;
                }
            }
            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;
    }
    

    【第一步】 对Key求Hash值,然后再计算下标

    putVal的第一个参数是根据Key的hashcode计算一个新的hashcode,源码如下:

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

    在JDK1.8之前,重新计算hashcode源码是这样的

        final int hash(Object k) {
            int h = 0;
            if (useAltHashing) {
                if (k instanceof String) {
                    return sun.misc.Hashing.stringHash32((String) k);
                }
                h = hashSeed;
            }
            //得到k的hashcode值
            h ^= k.hashCode();
            //进行计算
            h ^= (h >>> 20) ^ (h >>> 12);
            return h ^ (h >>> 7) ^ (h >>> 4);
        }
    

    计算数组下标代码如下:

    在JDK1.8之前的源码是:

    static int indexFor(int h, int length) {  
        return h & (length-1);
    }
    

    在JDK1.8之后,计算数组下标的代码在putVal中,

    tab[i = (n - 1) & hash]
    

    n是数组的长度,hash的重新计算后的hashcode。

    所以,计算数组下标的算法是:

    index =  hashcode & (length-1)
    

    该算法相当于

    index =  hashcode % length
    

    那么,问题来了,为什么不直接使用key的hashcode?为什么JDK1.8前后会有差异?

    原因只有一个:为了让Hash表更加散列,减少冲突(碰撞)次数。

    如果hashcode没有重新计算,假设某对象的hashcode是3288498,那么对应的二进制是:

    1100100010110110110010
    

    hashmap的长度默认为16,所以假设length = 16,hashcode & (length-1)的运算如下:

      1100100010110110110010
    & 0000000000000000001111
    --------------------------------------
      0000000000000000000010
    

    以上计算结果是十进制2,即数组下标为2。因此,我们发现的现象是:计算数组角标的计算,其实就是低位在计算,当前是在低4位上进行运算。

    当数组长度为8时,在第3位计算出数组下标;
    当数组长度为16时,在第4位计算出数组下标;
    当数组长度为32时,在第5位计算出数组下标;
    当数组长度为64时,在第6位计算出数组下标;

    以此类推...

    为了让HashMap的存储更加散列,即低n位更加散列,需要和高m位进行异或运算,最终得出新的hashcode。这就是要重新计算hashcode的原因。JDK1.8前后重新计算hashcode算法的差异是因为,JDK1.8的hash算法比JDK1.8之前的hash算法更能让HashMap的存储更加散列,避免存储空间的拥挤,减少碰撞的发生。

    【第二步】 碰撞的处理

    Java中HashMap是利用“拉链法”处理HashCode的碰撞问题。在调用HashMap的put方法或get方法时,都会首先调用hashcode方法,去查找相关的key,当有冲突时,再调用equals方法。hashMap基于hasing原理,我们通过put和get方法存取对象。当我们将键值对传递给put方法时,他调用键对象的hashCode()方法来计算hashCode,然后找到bucket(哈希桶)位置来存储对象。当获取对象时,通过键对象的equals()方法找到正确的键值对,然后返回值对象。HashMap使用链表来解决碰撞问题,当碰撞发生了,对象将会存储在链表的下一个节点中。hashMap在每个链表节点存储键值对对象。当两个不同的键却有相同的hashCode时,他们会存储在同一个bucket位置的链表中。

    【第三步】 如果链表长度超过阀值( TREEIFY THRESHOLD==8),就把链表转成红黑树,链表长度低于6,就把红黑树转回链表

    /**
     * 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;
    
    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
        //红黑树
        treeifyBin(tab, hash);
    

    在JDK1.8之后,HashMap的存储引入了红黑树数据结构。

    【第四步】 如果节点已经存在就替换旧值

    代码如下:

            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
    

    【第五步】 扩容

    代码如下:

    /**
     * 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;
        //定义新容量和阈值
        int newCap, newThr = 0;
        if (oldCap > 0) {//如果当前容量>0
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            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
            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) {
                    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;
    }
    

    以上扩容相关代码是基于JDK1.8的,和JDK1.8之前存在差异。

    (3)获取元素
    /**
     * Returns the value to which the specified key is mapped,
     * or {@code null} if this map contains no mapping for the key.
     *
     * <p>More formally, if this map contains a mapping from a key
     * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
     * key.equals(k))}, then this method returns {@code v}; otherwise
     * it returns {@code null}.  (There can be at most one such mapping.)
     *
     * <p>A return value of {@code null} does not <i>necessarily</i>
     * indicate that the map contains no mapping for the key; it's also
     * possible that the map explicitly maps the key to {@code null}.
     * The {@link #containsKey containsKey} operation may be used to
     * distinguish these two cases.
     *
     * @see #put(Object, Object)
     */
    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
    
    /**
     * 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;
        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);
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }
    

    获取元素其实,没什么好讲的,但是需要知道的是,不管是插入元素还是获取元素,都是围绕节点(Node)来操作的。Node实现了Map.Entry<K,V>接口。

    (4)遍历元素

    【方法一】

    如果只需要获取所有的key,最佳方案如下:

        for (Integer key : map.keySet()) {//在for-each循环中遍历keys
            System.out.println(String.valueOf(key));
        }
    

    优点:比entrySet遍历要快,代码简洁。

    【方法二】

    如果只需要获取所有的value,最佳方案如下:

        for (String value : map.values()) {//在for-each循环中遍历value
            System.out.println(value);
        }
    

    优点:比entrySet遍历要快,代码简洁。

    【方法三】

    通过键找值遍历

        for (Integer key : map.keySet()) {//在for-each循环中遍历keys
            String value = map.get(key);
            System.out.println(key+"========"+value);
        }
    

    缺点:根据键取值是耗时操作,效率非常的慢, 所以不推荐。

    【方法四】

    通过Map.entrySet遍历key和value

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

    优点:代码简洁,效率高,推荐使用。

    【方法五】

    使用Iterator遍历

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

    缺点:代码比起前面几个方法并不简洁。
    优点:当遍历的时候,如果涉及到删除操作,建议使用Iterator的remove方法,因为如果使用foreach的话会报错。

    最后,一个比较重要的就是HashMap的面试题了,大家可以自行百度。

    比如:

    HashMap 相关面试题及其解答

    [本章完...]

    相关文章

      网友评论

          本文标题:HashMap源码分析

          本文链接:https://www.haomeiwen.com/subject/ntdgnctx.html