一些对HashMap的理解

7 篇文章 0 订阅

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,然后进行

判断当前哈希桶是否为空,再进行新建头结点。否则进行判断比对,符合条件就覆盖结点e,否则用instanceof

关键字进行判断p是否为当前哈希桶存储的(红黑树)TreeNode,接着放进该红黑树中,其实用红黑树结点代替哈希桶

元素结点的时候的条件源码已经给出了,即使binCount>TREEIFY_THRESHOLD - 1,即当前哈希桶元素(不包含头结点)

大于等于7个就进行treeifyBin(tab, hash)函数进行树形化,树形化后,哈希桶的元素的存储结构就为红黑树了,

而不是链表了。而当整个哈希表的容量大于等于MIN_TREEIFY_CAPACITY = 64这个值之后,整个哈希表就树形化了。

前面的instanceof需要在树形化之后才能判断,因为树形化之前TreeNode都是null。如果没放进红黑树,那么就作为头结点插入。

//一个桶的树化阈值
//当桶中元素个数超过这个值时,需要使用红黑树节点替换链表节点
//这个值必须为 8,要不然频繁转换效率也不高
static final int TREEIFY_THRESHOLD = 8;

//一个树的链表还原阈值
//当扩容时,桶中元素个数小于这个值,就会把树形的桶元素 还原(切分)为链表结构
//这个值应该比上面那个小,至少为 6,避免频繁转换
static final int UNTREEIFY_THRESHOLD = 6;

//哈希表的最小树形化容量
//当哈希表中的容量大于这个值时,表中的桶才能进行树形化
//否则桶内元素太多时会扩容,而不是树形化
//为了避免进行扩容、树形化选择的冲突,这个值不能小于 4 * TREEIFY_THRESHOLD
static final int MIN_TREEIFY_CAPACITY = 64;
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。


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

源代码注释中写到,get返回值是null的话,那么这个key对应的值可能是null,也可能不存在这个key

所以,进而还需要用containsKey方法判断这个key是否存在。

删除
/**
    * Implements Map.remove and related methods
    *
    * @param hash hash for key
    * @param key the key
    * @param value the value to match if matchValue, else ignored
    * @param matchValue if true only remove if value is equal
    * @param movable if false do not move other nodes while removing
    * @return the node, or null if none
    */
   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;
       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;
           if (p.hash == hash &&
               ((k = p.key) == key || (key != null && key.equals(k))))
               node = p;
           else if ((e = p.next) != null) {
               if (p instanceof TreeNode)
                   node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
               else {
                   do {
                       if (e.hash == hash &&
                           ((k = e.key) == key ||
                            (key != null && key.equals(k)))) {
                           node = e;
                           break;
                       }
                       p = e;
                   } while ((e = e.next) != null);
               }
           }
           if (node != null && (!matchValue || (v = node.value) == value ||
                                (value != null && value.equals(v)))) {
               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;
   }

传入相关key,通过hashCode找到位置,然后再判断该位置的value是否只有一个,接着进行删除。删除的时候还需要
判断相对应的key值和enquals比较,因为同一个哈希桶中可能存在key值相同,但是对象可能不同,所以药用enquals
比较,删除相对应的结点后,头指针指向下一个结点。

部分参考自博文:彻头彻尾理解 HashMap

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值