一些对HashMap的理解

HashMap

HashMap继承于抽象类AbstractMap,而该抽象类实现了Map接口。
Map是Key-Value对映射的抽象接口,映射不包含重复的键。即存储的对象是Entry(同时包含了key和value)

HashMap最多允许一条Entry的Key为null(多条覆盖),允许多条Entry的value为null。HashMap不是线程安全的Map


1.构造方法

   /**
      * Constructs an empty {@code HashMap} 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);
     }

     /**
      * Constructs an empty {@code HashMap} 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);
     }

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

     /**
      * Constructs a new {@code HashMap} with the same mappings as the
      * specified {@code Map}.  The {@code HashMap} is created with
      * default load factor (0.75) and an initial capacity sufficient to
      * hold the mappings in the specified {@code Map}.
      *
      * @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);
     }

看三个构造方法都出现了initial capacity和load factor,前者是初始容量,后者是负载因子,HashMap的容量必须是2的幂次方容量表示哈希表中桶的数量 (table 数组的大小),初始容量是创建哈希表时桶的数量;负载因子是哈希表在其容量自动增加之前可以达到多满的一种尺度,它衡量的是一个散列表的空间的使用程度,负载因子越大表示散列表的装填程度越高,反之愈小。

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

    //所以初始容量是16,2的四次方,因为二进制中1左移了4位

虽然容器中存储的是JAVA对象,但是容器不会把对象放进去,而是保留这些对象的引用,即引用变量,这点要清楚。


2.HashMap的数据结构

我们看下HashMap的插入函数put的一部分:

/**
    * 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);

   }

源码可以看出,先new一个Node数组tab和相应的Node结点p,以及存放数组的长度变量n

其实这个Node就是一个实现了Map.Entry

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

这样子看来HashMap的实现就是链表数组,每一个数组的元素中存放着一条链表的头结点(实际上就是一条链表)!
那为什么这么做呢??因为数组是寻址容易,直接查找对应的下标呀,但是插入和删除对应的元素困难,而链表则相反,插入和删除容易,寻址困难。所以HashMap结合了两者的优点来实现,使用了哈希表来实现。哈希表有很多种实现的方法,其中最经典的就是

拉链法(可以理解为存储链表的数组)

我们可以从上图看到,左边很明显是个数组,数组的每个成员是一个链表。该数据结构所容纳的所有元素均包含一个指针

用于元素间的链接。我们根据元素的自身特征把元素分配到不同的链表中去,反过来我们也正是通过这些特征找到正确的

链表,再从链表中找出正确的元素。其中,根据元素特征计算元素数组下标的方法就是 哈希算法。

  总的来说,哈希表适合用作快速查找、删除的基本数据结构,通常需要总数据量可以放入内存。在使用哈希表时,有以下几个关键点:

hash 函数(哈希算法)的选择:针对不同的对象(字符串、整数等)具体的哈希方法;

碰撞处理:常用的有两种方式,一种是open hashing,即 >拉链法;另一种就是 closed hashing,即开地址法(opened addressing)。

其中构造函数中的initial capacity(初始容量)相当于数组的长度,我们看最后一个构造方法的putMapEntries(m, false);

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
                    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);
                }
            }
        }
        //table的定义。
        transient Node<K,V>[] table;

Node对应定义我们在上面已经给出了。所以可以明确知道HashMap中存储的元素是实现了Map.Entry

HashMap插入和查询的过程

插入

我们都知道,HashMap中可以允许一个key有多个value。也就是key是唯一的。

那么如何保证唯一性呢?我们可能想到,插入的时候比较一下,这个想法可以是可以,但是如果数据量大了呢?

毕竟HashMap的最大容量是2的32次方!!!如果插入的时候比较,那么势必会造成性能的低下。所以HashMap

采用了哈希算法来实现插入,源码时间:


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

可以看到插入的时候,调用了putVal函数,并且传进去了一个hash(key),继续追踪这个hash()方法

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

其实hash()方法就是根据key生成一个int类型的hashCode,具体的实现有兴趣的同学可以上网查看。

那么HashMap就根据这个hashCode快速找到哈希表中对应的桶(即数组对应的index),如果两个对象的hashCode不同

那么equals一定为 false;否则,如果其hashCode相同,equals也不一定为 true。所以,理论上,hashCode

可能存在碰撞的情况,当碰撞发生时,这时会取出Index桶内已存储的元素,并通过hashCode() 和 equals()
来逐个比较以判断Key是否已存在。如果已存在,则使用新Value值替换旧Value值,并返回旧Value值;

如果不存在,则存放新的键值对

插入的过程:

先判断HashMap中的链表数组是否为空,空的话就调用resize()函数并返回一个链表数组赋值给tab,

HashMap的扩容函数resize:

调用场景:哈希表为空或者key数量大于哈希表数量X负载因子

扩容的原因:随着HashMap中元素的数量越来越多,发生碰撞的概率将越来越大,所产生的子链长度就会越来越长

这样势必会影响HashMap的存取速度。为了保证HashMap的效率,系统必须要在某个临界点进行扩容处理,该临界点就
是HashMap中元素的数量在数值上等于threshold(table数组长度*负载因子)。
但是,不得不说,扩容是一个

非常耗时的过程,因为它需要重新计算这些元素在新table数组中的位置并进行复制处理。所以,如果我们能够

提前预知HashMap 中元素的个数,那么在构造HashMap时预设元素的个数能够有效的提高HashMap的性能。

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) {
            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) // 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;
    }

并且赋值扩容后的数组tab的长度给n。接着取出相对应的hashCode的元素,并且判断是否为空,

此时p赋值为tab[i],空的话就新建一个node放置在tab[i]上

此时tab[i]上存储了元素p,p包含了key,value,hash,以及指向下一个链表结点的next指针。

如果插入的时候,相对应的hashCode的位置上存在元素,那么就比较tab[i]的元素和插入的key的hashCode,key

(这里调用了equals比较key值)都相同的话那么p就覆盖e,此时e由空节点变为上一次插入的有数据的结点,

接下来再判断e的value是否为空,然后把传进来的value覆盖e的value,接着调用afterNodeAccess函数,该函数是使新节点指向旧结点,所以e变成了链头,接着再判断哈希表的长度,是否再扩容。

其实value插入HashMap中的时候,在tab[i]中也会生成一个LinkedHashMap来管理以及参与HashMap的插入。

具体的实现可以看

彻头彻尾理解LinkedHashMap

理解了这个那么就会对HashMap有一个整体深刻的认识!

查询

查询就比较简单了,根据传进来的key,再根据key的hashCode在哈希表中定位到相对应的桶,然后返回value。

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

部分参考自博文:

彻头彻尾理解HashMap

猜你喜欢

转载自blog.csdn.net/callmeMrLu/article/details/81413430