zoukankan      html  css  js  c++  java
  • Java 集合系列 09 HashMap详细介绍(源码解析)和使用示例

    java 集合系列目录:

    Java 集合系列 01 总体框架

    Java 集合系列 02 Collection架构

    Java 集合系列 03 ArrayList详细介绍(源码解析)和使用示例

    Java 集合系列 04 LinkedList详细介绍(源码解析)和使用示例 

    Java 集合系列 05 Vector详细介绍(源码解析)和使用示例

    Java 集合系列 06 Stack详细介绍(源码解析)和使用示例

    Java 集合系列 07 List总结(LinkedList, ArrayList等使用场景和性能分析)

    Java 集合系列 08 Map架构

    Java 集合系列 09 HashMap详细介绍(源码解析)和使用示例

    Java 集合系列 10 Hashtable详细介绍(源码解析)和使用示例

    Java 集合系列 11 hashmap 和 hashtable 的区别

    Java 集合系列 12 TreeMap

    Java 集合系列 13 WeakHashMap

    Java 集合系列 14 hashCode

    Java 集合系列 15 Map总结

    Java 集合系列 16 HashSet

    Java 集合系列 17 TreeSet

    概要

    这一章,我们对HashMap进行学习。
    我们先对HashMap有个整体认识,然后再学习它的源码,最后再通过实例来学会使用HashMap。内容包括:

    第1部分 HashMap介绍
    第2部分 HashMap数据结构
    第3部分 HashMap源码解析(基于JDK1.7.0_45)
        第3.1部分 HashMap的“拉链法”相关内容
        第3.2部分 HashMap的构造函数
        第3.3部分 HashMap的主要对外接口
        第3.4部分 HashMap实现的Cloneable接口
        第3.5部分 HashMap实现的Serializable接口
    第4部分 HashMap遍历方式

    第5部分 HashMap实例演示

    第1部分 HashMap介绍

    HashMap简介

    HashMap 是一个散列表,它存储的内容是键值对(key-value)映射。
    HashMap 继承于AbstractMap,实现了Map、Cloneable、java.io.Serializable接口。
    HashMap 的实现不是同步的,这意味着它不是线程安全的。它的key、value都可以为null。此外,HashMap中的映射不是有序的。

    HashMap 的实例有两个参数影响其性能:“初始容量” 和 “加载因子”。容量 是哈希表中桶的数量,初始容量 只是哈希表在创建时的容量。加载因子 是哈希表在其容量自动增加之前可以达到多满的一种尺度。当哈希表中的条目数超出了加载因子与当前容量的乘积时,则要对该哈希表进行 rehash 操作(即重建内部数据结构),从而哈希表将具有大约两倍的桶数。
    通常,默认加载因子是 0.75, 这是在时间和空间成本上寻求一种折衷。加载因子过高虽然减少了空间开销,但同时也增加了查询成本(在大多数 HashMap 类的操作中,包括 get 和 put 操作,都反映了这一点)。在设置初始容量时应该考虑到映射中所需的条目数及其加载因子,以便最大限度地减少 rehash 操作次数。如果初始容量大于最大条目数除以加载因子,则不会发生 rehash 操作。

    HashMap的构造函数

    HashMap共有4个构造函数,如下:

    // 默认构造函数。
    HashMap()
    
    // 指定“容量大小”的构造函数
    HashMap(int capacity)
    
    // 指定“容量大小”和“加载因子”的构造函数
    HashMap(int capacity, float loadFactor)
    
    // 包含“子Map”的构造函数
    HashMap(Map<? extends K, ? extends V> map)

    HashMap的API

     void clear() 
              从此映射中移除所有映射关系。 
     Object clone() 
              返回此 HashMap 实例的浅表副本:并不复制键和值本身。 
     boolean containsKey(Object key) 
              如果此映射包含对于指定键的映射关系,则返回 trueboolean containsValue(Object value) 
              如果此映射将一个或多个键映射到指定值,则返回 true。 
     Set<Map.Entry<K,V>> entrySet() 
              返回此映射所包含的映射关系的 Set 视图。 
     V get(Object key) 
              返回指定键所映射的值;如果对于该键来说,此映射不包含任何映射关系,则返回 nullboolean isEmpty() 
              如果此映射不包含键-值映射关系,则返回 true。 
     Set<K> keySet() 
              返回此映射中所包含的键的 Set 视图。 
     V put(K key, V value) 
              在此映射中关联指定值与指定键。 
     void putAll(Map<? extends K,? extends V> m) 
              将指定映射的所有映射关系复制到此映射中,这些映射关系将替换此映射目前针对指定映射中所有键的所有映射关系。 
     V remove(Object key) 
              从此映射中移除指定键的映射关系(如果存在)。 
     int size() 
              返回此映射中的键-值映射关系数。 
     Collection<V> values() 
              返回此映射所包含的值的 Collection 视图。 

    第2部分 HashMap数据结构

     HashMap的继承关系

    java.lang.Object
       ↳     java.util.AbstractMap<K, V>
             ↳     java.util.HashMap<K, V>
    
    public class HashMap<K,V>
        extends AbstractMap<K,V>
        implements Map<K,V>, Cloneable, Serializable { }

    HashMap与Map关系如下图

    从图中可以看出: 
    (01) HashMap继承于AbstractMap类,实现了Map接口。Map是"key-value键值对"接口,AbstractMap实现了"键值对"的通用函数接口。 
    (02) HashMap是通过"拉链法"实现的哈希表。它包括几个重要的成员变量:tablesizethresholdloadFactormodCount
      table是一个Entry[]数组类型,而Entry实际上就是一个单向链表。哈希表的"key-value键值对"都是存储在Entry数组中的。 
      size是HashMap的大小,它是HashMap保存的键值对的数量。 
      threshold是HashMap的阈值,用于判断是否需要调整HashMap的容量。threshold的值="容量*加载因子",当HashMap中存储数据的数量达到threshold时,就需要将HashMap的容量加倍。
      loadFactor就是加载因子。 
      modCount是用来实现fail-fast机制的。

    第3部分 HashMap源码解析(基于JDK1.7.0_45)

     为了更了解HashMap的原理,下面对HashMap源码代码作出分析。

    第3.1部分 HashMap的“拉链法”相关内容 

    transient Entry[] table;

    HashMap中的key-value都是存储在Entry数组中的。

    3.1.2 数据节点Entry的数据结构

     1     static class Entry<K,V> implements Map.Entry<K,V> {
     2         final K key;
     3         V value;
     4         Entry<K,V> next;
     5         int hash;
     6 
     7         /**
     8          * Creates new entry.
     9          */
    10         Entry(int h, K k, V v, Entry<K,V> n) {
    11             value = v;
    12             next = n;
    13             key = k;
    14             hash = h;
    15         }
    16 
    17         public final K getKey() {
    18             return key;
    19         }
    20 
    21         public final V getValue() {
    22             return value;
    23         }
    24 
    25         public final V setValue(V newValue) {
    26             V oldValue = value;
    27             value = newValue;
    28             return oldValue;
    29         }
    30         
    31             //判断两个Entry是否相等
    32      // 若两个Entry的“key”和“value”都相等,则返回true。
    33      // 否则,返回false
    34         public final boolean equals(Object o) {
    35             if (!(o instanceof Map.Entry))
    36                 return false;
    37             Map.Entry e = (Map.Entry)o;
    38             Object k1 = getKey();
    39             Object k2 = e.getKey();
    40             if (k1 == k2 || (k1 != null && k1.equals(k2))) {
    41                 Object v1 = getValue();
    42                 Object v2 = e.getValue();
    43                 if (v1 == v2 || (v1 != null && v1.equals(v2)))
    44                     return true;
    45             }
    46             return false;
    47         }
    48 
    49         public final int hashCode() {
    50             return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
    51         }
    52 
    53         public final String toString() {
    54             return getKey() + "=" + getValue();
    55         }
    56 
    57         /**
    58          * This method is invoked whenever the value in an entry is
    59          * overwritten by an invocation of put(k,v) for a key k that's already
    60          * in the HashMap.
    61          */
    62         void recordAccess(HashMap<K,V> m) {
    63         }
    64 
    65         /**
    66          * This method is invoked whenever the entry is
    67          * removed from the table.
    68          */
    69         void recordRemoval(HashMap<K,V> m) {
    70         }
    71     }

    从中,我们可以看出 Entry 实际上就是一个单向链表。这也是为什么我们说HashMap是通过拉链法解决哈希冲突的。
    Entry 实现了Map.Entry 接口,即实现getKey(), getValue(), setValue(V value), equals(Object o), hashCode()这些函数。这些都是基本的读取/修改key、value值的函数。

    第3.2部分 HashMap的构造函数

    HashMap共包括4个构造函数

     1 /**
     2      * Constructs an empty <tt>HashMap</tt> with the specified initial
     3      * capacity and load factor.
     4      *
     5      * @param  initialCapacity the initial capacity
     6      * @param  loadFactor      the load factor
     7      * @throws IllegalArgumentException if the initial capacity is negative
     8      *         or the load factor is nonpositive
     9      */
    10     public HashMap(int initialCapacity, float loadFactor) {
    11         if (initialCapacity < 0)
    12             throw new IllegalArgumentException("Illegal initial capacity: " +
    13                                                initialCapacity);
    14         if (initialCapacity > MAXIMUM_CAPACITY)
    15             initialCapacity = MAXIMUM_CAPACITY;
    16         if (loadFactor <= 0 || Float.isNaN(loadFactor))
    17             throw new IllegalArgumentException("Illegal load factor: " +
    18                                                loadFactor);
    19 
    20         this.loadFactor = loadFactor;
    21         threshold = initialCapacity;
    22         init();
    23     }
    24 
    25     /**
    26      * Constructs an empty <tt>HashMap</tt> with the specified initial
    27      * capacity and the default load factor (0.75).
    28      *
    29      * @param  initialCapacity the initial capacity.
    30      * @throws IllegalArgumentException if the initial capacity is negative.
    31      */
    32     public HashMap(int initialCapacity) {
    33         this(initialCapacity, DEFAULT_LOAD_FACTOR);
    34     }
    35 
    36     /**
    37      * Constructs an empty <tt>HashMap</tt> with the default initial capacity
    38      * (16) and the default load factor (0.75).
    39      */
    40     public HashMap() {
    41         this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
    42     }
    43 
    44     /**
    45      * 包含“子Map”的构造函数
    46      */
    47     public HashMap(Map<? extends K, ? extends V> m) {
    48         this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
    49                       DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
    50         inflateTable(threshold);
    51 
    52         putAllForCreate(m);
    53     }

    第3.3部分 HashMap的主要对外接口

    3.3.1 clear()

    clear() 的作用是清空HashMap。它是通过将所有的元素设为null来实现的。

     1  /**
     2      * Removes all of the mappings from this map.
     3      * The map will be empty after this call returns.
     4      */
     5     public void clear() {
     6         modCount++;
     7         Arrays.fill(table, null);
     8         size = 0;
     9     }
    10    
    11    /**
    12      * Assigns the specified Object reference to each element of the specified
    13      * array of Objects.
    14      *
    15      * @param a the array to be filled
    16      * @param val the value to be stored in all elements of the array
    17      * @throws ArrayStoreException if the specified value is not of a
    18      *         runtime type that can be stored in the specified array
    19      */
    20     public static void fill(Object[] a, Object val) {
    21         for (int i = 0, len = a.length; i < len; i++)
    22             a[i] = val;
    23     }

    3.3.2 containsKey()

    containsKey() 的作用是判断HashMap是否包含key

     1 /**
     2      * Returns <tt>true</tt> if this map contains a mapping for the
     3      * specified key.
     4      *
     5      * @param   key   The key whose presence in this map is to be tested
     6      * @return <tt>true</tt> if this map contains a mapping for the specified
     7      * key.
     8      */
     9     public boolean containsKey(Object key) {
    10         return getEntry(key) != null;
    11     }
    12   final Entry<K,V> getEntry(Object key) {
    13         if (size == 0) {
    14             return null;
    15         }
    16 
    17         int hash = (key == null) ? 0 : hash(key);
    18         for (Entry<K,V> e = table[indexFor(hash, table.length)];
    19              e != null;
    20              e = e.next) {
    21             Object k;
    22             if (e.hash == hash &&
    23                 ((k = e.key) == key || (key != null && key.equals(k))))
    24                 return e;
    25         }
    26         return null;
    27     }

    3.3.4 entrySet()、values()、keySet()

    它们3个的原理类似,这里以entrySet()为例来说明。
    entrySet()的作用是返回“HashMap中所有Entry的集合”,它是一个集合。实现代码如下:

     1 // 返回“HashMap的Entry集合”
     2 public Set<Map.Entry<K,V>> entrySet() {
     3     return entrySet0();
     4 }
     5 
     6 // 返回“HashMap的Entry集合”,它实际是返回一个EntrySet对象
     7 private Set<Map.Entry<K,V>> entrySet0() {
     8     Set<Map.Entry<K,V>> es = entrySet;
     9     return es != null ? es : (entrySet = new EntrySet());
    10 }
    11 
    12 // EntrySet对应的集合
    13 // EntrySet继承于AbstractSet,说明该集合中没有重复的EntrySet。
    14 private final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
    15     public Iterator<Map.Entry<K,V>> iterator() {
    16         return newEntryIterator();
    17     }
    18     public boolean contains(Object o) {
    19         if (!(o instanceof Map.Entry))
    20             return false;
    21         Map.Entry<K,V> e = (Map.Entry<K,V>) o;
    22         Entry<K,V> candidate = getEntry(e.getKey());
    23         return candidate != null && candidate.equals(e);
    24     }
    25     public boolean remove(Object o) {
    26         return removeMapping(o) != null;
    27     }
    28     public int size() {
    29         return size;
    30     }
    31     public void clear() {
    32         HashMap.this.clear();
    33     }
    34 }

    HashMap是通过拉链法实现的散列表。表现在HashMap包括许多的Entry,而每一个Entry本质上又是一个单向链表。那么HashMap遍历key-value键值对的时候,是如何逐个去遍历的呢?


    下面我们就看看HashMap是如何通过entrySet()遍历的。
    entrySet()实际上是通过newEntryIterator()实现的。 下面我们看看它的代码:

     1 // 返回一个“entry迭代器”
     2 Iterator<Map.Entry<K,V>> newEntryIterator()   {
     3     return new EntryIterator();
     4 }
     5 
     6 // Entry的迭代器
     7 private final class EntryIterator extends HashIterator<Map.Entry<K,V>> {
     8     public Map.Entry<K,V> next() {
     9         return nextEntry();
    10     }
    11 }
    12 
    13 // HashIterator是HashMap迭代器的抽象出来的父类,实现了公共了函数。
    14 // 它包含“key迭代器(KeyIterator)”、“Value迭代器(ValueIterator)”和“Entry迭代器(EntryIterator)”3个子类。
    15 private abstract class HashIterator<E> implements Iterator<E> {
    16     // 下一个元素
    17     Entry<K,V> next;
    18     // expectedModCount用于实现fast-fail机制。
    19     int expectedModCount;
    20     // 当前索引
    21     int index;
    22     // 当前元素
    23     Entry<K,V> current;
    24 
    25     HashIterator() {
    26         expectedModCount = modCount;
    27         if (size > 0) { // advance to first entry
    28             Entry[] t = table;
    29             // 将next指向table中第一个不为null的元素。
    30             // 这里利用了index的初始值为0,从0开始依次向后遍历,直到找到不为null的元素就退出循环。
    31             while (index < t.length && (next = t[index++]) == null)
    32                 ;
    33         }
    34     }
    35 
    36     public final boolean hasNext() {
    37         return next != null;
    38     }
    39 
    40     // 获取下一个元素
    41     final Entry<K,V> nextEntry() {
    42         if (modCount != expectedModCount)
    43             throw new ConcurrentModificationException();
    44         Entry<K,V> e = next;
    45         if (e == null)
    46             throw new NoSuchElementException();
    47 
    48         // 注意!!!
    49         // 一个Entry就是一个单向链表
    50         // 若该Entry的下一个节点不为空,就将next指向下一个节点;
    51         // 否则,将next指向下一个链表(也是下一个Entry)的不为null的节点。
    52         if ((next = e.next) == null) {
    53             Entry[] t = table;
    54             while (index < t.length && (next = t[index++]) == null)
    55                 ;
    56         }
    57         current = e;
    58         return e;
    59     }
    60 
    61     // 删除当前元素
    62     public void remove() {
    63         if (current == null)
    64             throw new IllegalStateException();
    65         if (modCount != expectedModCount)
    66             throw new ConcurrentModificationException();
    67         Object k = current.key;
    68         current = null;
    69         HashMap.this.removeEntryForKey(k);
    70         expectedModCount = modCount;
    71     }
    72 
    73 }

    当我们通过entrySet()获取到的Iterator的next()方法去遍历HashMap时,实际上调用的是 nextEntry() 。而nextEntry()的实现方式,先遍历Entry(根据Entry在table中的序号,从小到大的遍历);然后对每个Entry(即每个单向链表),逐个遍历。


    3.3.5 get()

    get() 的作用是获取key对应的value,它的实现代码如下:

     1 /**
     2      * Returns the value to which the specified key is mapped,
     3      * or {@code null} if this map contains no mapping for the key.
     4      *
     5      * <p>More formally, if this map contains a mapping from a key
     6      * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
     7      * key.equals(k))}, then this method returns {@code v}; otherwise
     8      * it returns {@code null}.  (There can be at most one such mapping.)
     9      *
    10      * 空返回值并不一定表明map不包含映射的关键;也有可能map上显式映射空的关键。
    11      * containsKey操作可以用来区分这两种情况下。
    12      */
    13     public V get(Object key) {
    14         if (key == null)
    15             return getForNullKey();
    16         Entry<K,V> entry = getEntry(key);
    17 
    18         return null == entry ? null : entry.getValue();
    19     }
    20     
    21     /**
    22      * Returns the entry associated with the specified key in the
    23      * HashMap.  Returns null if the HashMap contains no mapping
    24      * for the key.
    25      */
    26     final Entry<K,V> getEntry(Object key) {
    27         if (size == 0) {
    28             return null;
    29         }
    30             // 获取key的hash值
    31         int hash = (key == null) ? 0 : hash(key);
    32         // 在“该hash值对应的链表”上查找“键值等于key”的元素
    33         for (Entry<K,V> e = table[indexFor(hash, table.length)];
    34              e != null;
    35              e = e.next) {
    36             Object k;
    37             if (e.hash == hash &&
    38                 ((k = e.key) == key || (key != null && key.equals(k))))
    39                 return e;
    40         }
    41         return null;
    42     }

    3.3.6 put()

    put() 的作用是对外提供接口,让HashMap对象可以通过put()将“key-value”添加到HashMap中

     1     /**
     2      * Associates the specified value with the specified key in this map.
     3      * If the map previously contained a mapping for the key, the old
     4      * value is replaced.
     5      *
     6      * @param key key with which the specified value is to be associated
     7      * @param value value to be associated with the specified key
     8      * @return the previous value associated with <tt>key</tt>, or
     9      *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
    10      *         (A <tt>null</tt> return can also indicate that the map
    11      *         previously associated <tt>null</tt> with <tt>key</tt>.)
    12      */
    13     public V put(K key, V value) {
    14         if (table == EMPTY_TABLE) {
    15             inflateTable(threshold);
    16         }
    17         // 若“key为null”,则将该键值对添加到table[0]中。
    18         if (key == null)
    19             return putForNullKey(value);
    20         // 若“key不为null”,则计算该key的哈希值,然后将其添加到该哈希值对应的链表中。
    21         int hash = hash(key);
    22         int i = indexFor(hash, table.length);
    23         for (Entry<K,V> e = table[i]; e != null; e = e.next) {
    24             Object k;
    25             // 若“该key”对应的键值对已经存在,则用新的value取代旧的value。然后退出!
    26             if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
    27                 V oldValue = e.value;
    28                 e.value = value;
    29                 e.recordAccess(this);
    30                 return oldValue;
    31             }
    32         }
    33                 // 若“该key”对应的键值对不存在,则将“key-value”添加到table中
    34         modCount++;
    35         addEntry(hash, key, value, i);
    36         return null;
    37     }
    38     
    39      /**
    40      * Offloaded version of put for null keys
    41      */
    42     private V putForNullKey(V value) {
    43         for (Entry<K,V> e = table[0]; e != null; e = e.next) {
    44             if (e.key == null) {
    45                 V oldValue = e.value;
    46                 e.value = value;
    47                 e.recordAccess(this);
    48                 return oldValue;
    49             }
    50         }
    51         modCount++;
    52         addEntry(0, null, value, 0);
    53         return null;
    54     }
    55     
    56     /**
    57          * This method is invoked whenever the value in an entry is
    58          * overwritten by an invocation of put(k,v) for a key k that's already
    59          * in the HashMap.
    60          */
    61         void recordAccess(HashMap<K,V> m) {
    62         }

     若要添加到HashMap中的键值对对应的key已经存在HashMap中,则找到该键值对;然后新的value取代旧的value,并退出!
    若要添加到HashMap中的键值对对应的key不在HashMap中,则将其添加到该哈希值对应的链表中,并调用addEntry()。
    下面看看addEntry()的代码:

     1     /**
     2      * Adds a new entry with the specified key, value and hash code to
     3      * the specified bucket.  It is the responsibility of this
     4      * method to resize the table if appropriate.
     5      *
     6      * Subclass overrides this to alter the behavior of put method.
     7      */
     8     void addEntry(int hash, K key, V value, int bucketIndex) {
     9         if ((size >= threshold) && (null != table[bucketIndex])) {
    10             resize(2 * table.length);
    11             hash = (null != key) ? hash(key) : 0;
    12             bucketIndex = indexFor(hash, table.length);
    13         }
    14 
    15         createEntry(hash, key, value, bucketIndex);
    16     }

    addEntry() 的作用是新增Entry。将“key-value”插入指定位置,bucketIndex是位置索引。

    createEntry()的代码如下:

     1     /**
     2      * Like addEntry except that this version is used when creating entries
     3      * as part of Map construction or "pseudo-construction" (cloning,
     4      * deserialization).  This version needn't worry about resizing the table.
     5      *
     6      * Subclass overrides this to alter the behavior of HashMap(Map),
     7      * clone, and readObject.
     8      */
     9     void createEntry(int hash, K key, V value, int bucketIndex) {
    10             // 保存“bucketIndex”位置的值到“e”中
    11         Entry<K,V> e = table[bucketIndex];
    12         // 设置“bucketIndex”位置的元素为“新Entry”,
    13             // 设置“e”为“新Entry的下一个节点”
    14         table[bucketIndex] = new Entry<>(hash, key, value, e);
    15         size++;
    16     }

    它们的作用都是将key、value添加到HashMap中。而且,比较addEntry()和createEntry()的代码,我们发现addEntry()多了两句:

    if ((size >= threshold) && (null != table[bucketIndex]))
         resize(2 * table.length);

    那它们的区别到底是什么呢?
    阅读代码,可以发现它们的使用情景不同。
    (01) addEntry()一般用在 新增Entry可能导致“HashMap的实际容量”超过“阈值”的情况下。
           例如,我们新建一个HashMap,然后不断通过put()向HashMap中添加元素;put()是通过addEntry()新增Entry的。
           在这种情况下,我们不知道何时“HashMap的实际容量”会超过“阈值”;
           因此,需要调用addEntry()
    (02) createEntry() 一般用在 新增Entry不会导致“HashMap的实际容量”超过“阈值”的情况下。
            例如,我们调用HashMap“带有Map”的构造函数,它会将Map的全部元素添加到HashMap中;
           但在添加之前,我们已经计算好“HashMap的容量和阈值”。也就是,可以确定“即使将Map中的全部元素添加到HashMap中,都不会超过HashMap的阈值”。
           此时,调用createEntry()即可。

    3.3.7 putAll()

    putAll() 的作用是将"m"的全部元素都添加到HashMap中,它的代码如下:

     1     /**
     2      * Copies all of the mappings from the specified map to this map.
     3      * These mappings will replace any mappings that this map had for
     4      * any of the keys currently in the specified map.
     5      *
     6      * @param m mappings to be stored in this map
     7      * @throws NullPointerException if the specified map is null
     8      */
     9     public void putAll(Map<? extends K, ? extends V> m) {
    10     // 有效性判断
    11         int numKeysToBeAdded = m.size();
    12         if (numKeysToBeAdded == 0)
    13             return;
    14 
    15         if (table == EMPTY_TABLE) {
    16             inflateTable((int) Math.max(numKeysToBeAdded * loadFactor, threshold));
    17         }
    18 
    19         /*
    20          *  计算容量是否足够,若“当前实际容量 < 需要的容量”,则将容量x2。
    21          * Expand the map if the map if the number of mappings to be added
    22          * is greater than or equal to threshold.  This is conservative; the
    23          * obvious condition is (m.size() + size) >= threshold, but this
    24          * condition could result in a map with twice the appropriate capacity,
    25          * if the keys to be added overlap with the keys already in this map.
    26          * By using the conservative calculation, we subject ourself
    27          * to at most one extra resize.
    28          */
    29         if (numKeysToBeAdded > threshold) {
    30             int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
    31             if (targetCapacity > MAXIMUM_CAPACITY)
    32                 targetCapacity = MAXIMUM_CAPACITY;
    33             int newCapacity = table.length;
    34             while (newCapacity < targetCapacity)
    35                 newCapacity <<= 1;
    36             if (newCapacity > table.length)
    37                 resize(newCapacity);
    38         }
    39                 //通过迭代器,将“m”中的元素逐个添加到HashMap中。
    40         for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
    41             put(e.getKey(), e.getValue());
    42     }
    43     
    44     /**
    45      * Inflates the table.
    46      */
    47     private void inflateTable(int toSize) {
    48         // Find a power of 2 >= toSize
    49         int capacity = roundUpToPowerOf2(toSize);
    50 
    51         threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
    52         table = new Entry[capacity];
    53         initHashSeedAsNeeded(capacity);
    54     }
    55     
    56     **
    57      * Rehashes the contents of this map into a new array with a
    58      * larger capacity.  This method is called automatically when the
    59      * number of keys in this map reaches its threshold.
    60      */
    61     void resize(int newCapacity) {
    62         Entry[] oldTable = table;
    63         int oldCapacity = oldTable.length;
    64         if (oldCapacity == MAXIMUM_CAPACITY) {
    65             threshold = Integer.MAX_VALUE;
    66             return;
    67         }
    68 
    69         Entry[] newTable = new Entry[newCapacity];
    70         transfer(newTable, initHashSeedAsNeeded(newCapacity));
    71         table = newTable;
    72         threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
    73     }
    74     
    75     /**
    76      * Initialize the hashing mask value. We defer initialization until we
    77      * really need it.
    78      */
    79     final boolean initHashSeedAsNeeded(int capacity) {
    80         boolean currentAltHashing = hashSeed != 0;
    81         boolean useAltHashing = sun.misc.VM.isBooted() &&
    82                 (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
    83         boolean switching = currentAltHashing ^ useAltHashing;
    84         if (switching) {
    85             hashSeed = useAltHashing
    86                 ? sun.misc.Hashing.randomHashSeed(this)
    87                 : 0;
    88         }
    89         return switching;
    90     }

    3.3.8 remove()

    remove() 的作用是删除“键为key”元素

     1 public V remove(Object key) {
     2     Entry<K,V> e = removeEntryForKey(key);
     3     return (e == null ? null : e.value);
     4 }
     5 
     6 
     7 // 删除“键为key”的元素
     8 final Entry<K,V> removeEntryForKey(Object key) {
     9     // 获取哈希值。若key为null,则哈希值为0;否则调用hash()进行计算
    10     int hash = (key == null) ? 0 : hash(key.hashCode());
    11     int i = indexFor(hash, table.length);
    12     Entry<K,V> prev = table[i];
    13     Entry<K,V> e = prev;
    14 
    15     // 删除链表中“键为key”的元素
    16     // 本质是“删除单向链表中的节点”
    17     while (e != null) {
    18         Entry<K,V> next = e.next;
    19         Object k;
    20         if (e.hash == hash &&
    21             ((k = e.key) == key || (key != null && key.equals(k)))) {
    22             modCount++;
    23             size--;
    24             if (prev == e)
    25                 table[i] = next;
    26             else
    27                 prev.next = next;
    28             e.recordRemoval(this);
    29             return e;
    30         }
    31         prev = e;
    32         e = next;
    33     }
    34 
    35     return e;
    36 }

    第3.4部分 HashMap实现的Cloneable接口

     HashMap实现了Cloneable接口,即实现了clone()方法。
    clone()方法的作用就是克隆一个HashMap对象并返回。

     1 /**
     2      * Returns a shallow copy of this <tt>HashMap</tt> instance: the keys and
     3      * values themselves are not cloned.
     4      *
     5      * @return a shallow copy of this map
     6      */
     7     public Object clone() {
     8         HashMap<K,V> result = null;
     9         try {
    10             result = (HashMap<K,V>)super.clone();
    11         } catch (CloneNotSupportedException e) {
    12             // assert false;
    13         }
    14         if (result.table != EMPTY_TABLE) {
    15             result.inflateTable(Math.min(
    16                 (int) Math.min(
    17                     size * Math.min(1 / loadFactor, 4.0f),
    18                     // we have limits...
    19                     HashMap.MAXIMUM_CAPACITY),
    20                table.length));
    21         }
    22         result.entrySet = null;
    23         result.modCount = 0;
    24         result.size = 0;
    25         result.init();
    26     // 调用putAllForCreate()将全部元素添加到HashMap中
    27         result.putAllForCreate(this);
    28 
    29         return result;
    30     }
    31 
    32 private void putAllForCreate(Map<? extends K, ? extends V> m) {
    33         for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
    34             putForCreate(e.getKey(), e.getValue());
    35     }

    第3.5部分 HashMap实现的Serializable接口

    HashMap实现java.io.Serializable,分别实现了串行读取、写入功能。
    串行写入函数是writeObject(),它的作用是将HashMap的“总的容量,实际容量,所有的Entry”都写入到输出流中。
    而串行读取函数是readObject(),它的作用是将HashMap的“总的容量,实际容量,所有的Entry”依次读出

     1 // java.io.Serializable的写入函数
     2 // 将HashMap的“总的容量,实际容量,所有的Entry”都写入到输出流中
     3 private void writeObject(java.io.ObjectOutputStream s)
     4     throws IOException
     5 {
     6     Iterator<Map.Entry<K,V>> i =
     7         (size > 0) ? entrySet0().iterator() : null;
     8 
     9     // Write out the threshold, loadfactor, and any hidden stuff
    10     s.defaultWriteObject();
    11 
    12     // Write out number of buckets
    13     s.writeInt(table.length);
    14 
    15     // Write out size (number of Mappings)
    16     s.writeInt(size);
    17 
    18     // Write out keys and values (alternating)
    19     if (i != null) {
    20         while (i.hasNext()) {
    21         Map.Entry<K,V> e = i.next();
    22         s.writeObject(e.getKey());
    23         s.writeObject(e.getValue());
    24         }
    25     }
    26 }
    27 
    28 // java.io.Serializable的读取函数:根据写入方式读出
    29 // 将HashMap的“总的容量,实际容量,所有的Entry”依次读出
    30 private void readObject(java.io.ObjectInputStream s)
    31      throws IOException, ClassNotFoundException
    32 {
    33     // Read in the threshold, loadfactor, and any hidden stuff
    34     s.defaultReadObject();
    35 
    36     // Read in number of buckets and allocate the bucket array;
    37     int numBuckets = s.readInt();
    38     table = new Entry[numBuckets];
    39 
    40     init();  // Give subclass a chance to do its thing.
    41 
    42     // Read in size (number of Mappings)
    43     int size = s.readInt();
    44 
    45     // Read the keys and values, and put the mappings in the HashMap
    46     for (int i=0; i<size; i++) {
    47         K key = (K) s.readObject();
    48         V value = (V) s.readObject();
    49         putForCreate(key, value);
    50     }
    51 }

    第4部分 HashMap遍历方式

    4.1 遍历HashMap的键值对

    第一步:根据entrySet()获取HashMap的“键值对”的Set集合。
    第二步:通过Iterator迭代器遍历“第一步”得到的集合。

    public class hashmap_test {
        public static void main(String[] args) {
            HashMap<Integer, String> map = new HashMap<>();
            for (int i = 0; i < 5; i++) {
                map.put(i, Integer.valueOf(i).toString());
            }
            Iterator iter = map.entrySet().iterator();
            while(iter.hasNext()){
                Map.Entry entry = (Entry) iter.next();
                Integer key = (Integer) entry.getKey();
                String value = (String) entry.getValue();
            }
    
        }
    }

    4.2 遍历HashMap的键

    第一步:根据keySet()获取HashMap的“键”的Set集合。
    第二步:通过Iterator迭代器遍历“第一步”得到的集合。

     1 public class hashmap_test {
     2     public static void main(String[] args) {
     3         HashMap<Integer, String> map = new HashMap<>();
     4         for (int i = 0; i < 5; i++) {
     5             map.put(i, Integer.valueOf(i).toString());
     6         }
     7 
     8         Iterator iter = map.keySet().iterator();
     9         Integer key = null;
    10         String value = null;
    11         while(iter.hasNext()){
    12             key = (Integer) iter.next();
    13             value = map.get(key);
    14         }
    15     }
    16 }

    第5部分 HashMap实例演示

    我们来看个非常简单的例子。有一个”国家”(Country)类,我们将要用Country对象作为key,它的首都的名字(String类型)作为value。下面的例子有助于我们理解key-value对在HashMap中是如何存储的。

    1. Country.java

    /**
     * 
     * @ClassName: Country TODO
     * @author Xingle
     * @date 2014-7-4 下午4:32:10
     */
    public class Country {
    
        private String name;
    
        private long population;
    
        public Country(String name, long population) {
            super();
            this.name = name;
            this.population = population;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public long getPopulation() {
            return population;
        }
    
        public void setPopulation(long population) {
            this.population = population;
        }
    
        public int hashCode() {
            if (this.name.length() % 2 == 0)
                return 31;
            else
                return 95;
        }
    
        public boolean equals(Object obj) {
            Country other = (Country) obj;
            if (name.equals(other.getName()))
                return true;
            else
                return false;
        }
    }

    2. HashMapStructure.java

     1 /**
     2  * 
     3  * @ClassName: HashMapStructure TODO
     4  * @author Xingle
     5  * @date 2014-7-4 下午4:37:31
     6  */
     7 public class HashMapStructure {
     8 
     9     public static void main(String[] args){
    10         Country india = new Country("India", 1000);
    11         Country japan = new Country("Japan", 1000);
    12         Country france = new Country("France", 1000);
    13         Country russia = new Country("Russia", 1000);
    14         
    15         HashMap<Country, String> countryCapitalMap = new HashMap<Country, String>();
    16         countryCapitalMap.put(india, "Delhi");
    17         countryCapitalMap.put(japan,"Tokyo");
    18         countryCapitalMap.put(france,"Paris");
    19         countryCapitalMap.put(russia,"Moscow");
    20         
    21         //key迭代器
    22         Iterator<Country> countryCapitalIter = countryCapitalMap.keySet().iterator();
    23         while(countryCapitalIter.hasNext()){
    24             Country countryObj = countryCapitalIter.next();
    25             String capital = countryCapitalMap.get(countryObj);
    26             System.out.println(countryObj.getName()+"---"+countryObj.hashCode()+"----"+capital);
    27         }
    28         
    29     }
    30 }

    执行结果:

    Japan---95----Tokyo
    India---95----Delhi
    Russia---31----Moscow
    France---31----Paris

    现在,在第22行设置一个断点,debug下,查看countryCapitalMap,将会看到如下的结构:

    从上图可以观察到以下几点:

    1.table大小是16的Entry数组。这个table数组存储了Entry类的对象。HashMap类有一个叫做Entry的内部类。这个Entry类包含了key-value作为实例变量

    2.我们来看下Entry类的结构。Entry类的结构:

    static class Entry implements Map.Entry
    {
            final K key;
            V value;
            Entry next;
            final int hash;
            ...//More code goes here
    }   `

    每当往hashmap里面存放key-value对的时候,都会为它们实例化一个Entry对象,这个Entry对象就会存储在前面提到的Entry数组table中。那么,上面创建的Entry对象将会存放在具体哪个位置(在table中的精确位置)。答案就是,根据key的hashcode()方法计算出来的hash值(来决定)。hash值用来计算key在Entry数组的索引。
    现在,如果你看下上图中数组的索引10,它有一个叫做HashMap$Entry的Entry对象。
    我们往hashmap放了4个key-value对,但是看上去好像只有2个元素!!!这是因为,如果两个元素有相同的hashcode,它们会被放在同一个索引上,以链表(LinkedList)的形式来存储的(逻辑上)。
    上面的country对象的key-value的hash值是如何计算出来的。

    下图会清晰的从概念上解释下链表。

    现在假如你已经很好地了解了hashmap的结构,让我们看下put和get方法。

    Put :

    让我们看下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) {
      if (key == null)
       return putForNullKey(value);
      int hash = hash(key.hashCode());
      int i = indexFor(hash, table.length);
      for (Entry<k , V> e = table[i]; e != null; e = e.next) {
       Object k;
       if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
        V oldValue = e.value;
        e.value = value;
        e.recordAccess(this);
        return oldValue;
       }
      }
     
      modCount++;
      addEntry(hash, key, value, i);
      return null;
     }

    现在我们一步一步来看下上面的代码。

    1. 对key做null检查。如果key是null,会被存储到table[0],因为null的hash值总是0。

    2. key的hashcode()方法会被调用,然后计算hash值。hash值用来找到存储Entry对象的数组的索引。有时候hash函数可能写的很不好,所以JDK的设计者添加了另一个叫做hash()的方法,它接收刚才计算的hash值作为参数。如果你想了解更多关于hash()函数的东西,可以参考:hashmap中的hash和indexFor方法

    3. indexFor(hash,table.length)用来计算在table数组中存储Entry对象的精确的索引。

    4. 在我们的例子中已经看到,如果两个key有相同的hash值(也叫冲突),他们会以链表的形式来存储。所以,这里我们就迭代链表。

    • 如果在刚才计算出来的索引位置没有元素,直接把Entry对象放在那个索引上。
    • 如果索引上有元素,然后会进行迭代,一直到Entry->next是null。当前的Entry对象变成链表的下一个节点。
    • 如果我们再次放入同样的key会怎样呢?逻辑上,它应该替换老的value。事实上,它确实是这么做的。在迭代的过程中,会调用equals()方法来检查key的相等性(key.equals(k)),如果这个方法返回true,它就会用当前Entry的value来替换之前的value。

    Get:

    现在我们来看下get方法的实现:

    /**
      * 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><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) {
      if (key == null)
       return getForNullKey();
      int hash = hash(key.hashCode());
      for (Entry<k , V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) {
       Object k;
       if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
        return e.value;
      }
      return null;
     }

    当你理解了hashmap的put的工作原理,理解get的工作原理就非常简单了。当你传递一个key从hashmap总获取value的时候:

    1. 对key进行null检查。如果key是null,table[0]这个位置的元素将被返回。

    2. key的hashcode()方法被调用,然后计算hash值。

    3. indexFor(hash,table.length)用来计算要获取的Entry对象在table数组中的精确的位置,使用刚才计算的hash值。

    4. 在获取了table数组的索引之后,会迭代链表,调用equals()方法检查key的相等性,如果equals()方法返回true,get方法返回Entry对象的value,否则,返回null。

    要牢记以下关键点:

    • HashMap有一个叫做Entry的内部类,它用来存储key-value对。
    • 上面的Entry对象是存储在一个叫做table的Entry数组中。
    • table的索引在逻辑上叫做“桶”(bucket),它存储了链表的第一个元素。
    • key的hashcode()方法用来找到Entry对象所在的桶。
    • 如果两个key有相同的hash值,他们会被放在table数组的同一个桶里面。
    • key的equals()方法用来确保key的唯一性。
    • value对象的equals()和hashcode()方法根本一点用也没有。

     转载:http://www.cnblogs.com/skywang12345/p/3310835.html

  • 相关阅读:
    tp5使用jwt生成token,做api的用户认证
    thinkphp5.0多条件模糊查询以及多条件查询带分页如何保留参数
    tp5.1 模型 where多条件查询 like 查询 --多条件查询坑啊!!(tp5.1与tp5.0初始化控制器不一样)
    获取客户端IP地址-----以及--------线上开启redis扩展
    分享几个免费IP地址查询接口(API)
    thinkphp5选择redis库,让数据存入不同的redis库
    【JZOJ4824】【NOIP2016提高A组集训第1场10.29】配对游戏
    【JZOJ1637】【ZJOI2009】狼和羊的故事
    【JZOJ1611】Dining
    【JZOJ2224】【NOI2006】最大获利
  • 原文地址:https://www.cnblogs.com/xingele0917/p/3761122.html
Copyright © 2011-2022 走看看