java map的实现原理

HashMap 的实现原理

HashMap 概述

HashMap 是基于哈希表的 Map 接口的非同步实现。此实现提供所有可选的映射操作,并允许使用 null 值和 null 键。此类不保证映射的顺序,特别是它不保证该顺序恒久不变。

此实现假定哈希函数将元素适当地分布在各桶之间,可为基本操作(get 和 put)提供稳定的性能。迭代 collection 视图所需的时间与 HashMap 实例的“容量”(桶的数量)及其大小(键-值映射关系数)成比例。所以,如果迭代性能很重要,则不要将初始容量设置得太高或将加载因子设置得太低。也许大家开始对这段话有一点不太懂,不过不用担心,当你读完这篇文章后,就能深切理解这其中的含义了。

需要注意的是:Hashmap 不是同步的,如果多个线程同时访问一个 HashMap,而其中至少一个线程从结构上(指添加或者删除一个或多个映射关系的任何操作)修改了,则必须保持外部同步,以防止对映射进行意外的非同步访问。

HashMap 的数据结构

在 Java 编程语言中,最基本的结构就是两种,一个是数组,另外一个是指针(引用),HashMap 就是通过这两个数据结构进行实现。HashMap实际上是一个“链表散列”的数据结构,即数组和链表的结合体。

从上图中可以看出,HashMap 底层就是一个数组结构,数组中的每一项又是一个链表。当新建一个 HashMap 的时候,就会初始化一个数组。

我们通过 JDK 中的 HashMap 源码进行一些学习,首先看一下构造函数:

  1. public HashMap(int initialCapacity, float loadFactor) {

  2.  

    if (initialCapacity < 0)

  3.  

    throw new IllegalArgumentException("Illegal initial capacity: " +

  4.  

    initialCapacity);

  5.  

    if (initialCapacity > MAXIMUM_CAPACITY)

  6.  

    initialCapacity = MAXIMUM_CAPACITY;

  7.  

    if (loadFactor <= 0 || Float.isNaN(loadFactor))

  8.  

    throw new IllegalArgumentException("Illegal load factor: " +

  9.  

    loadFactor);

  10.  

  11.  

    // Find a power of 2 >= initialCapacity

  12.  

    int capacity = 1;

  13.  

    while (capacity < initialCapacity)

  14.  

    capacity <<= 1;

  15.  

  16.  

    this.loadFactor = loadFactor;

  17.  

    threshold = (int)Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);

  18.  

    table = new Entry[capacity];

  19.  

    useAltHashing = sun.misc.VM.isBooted() &&

  20.  

    (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);

  21.  

    init();

  22.  

    }

我们着重看一下第 18 行代码table = new Entry[capacity];。这不就是 Java 中数组的创建方式吗?也就是说在构造函数中,其创建了一个 Entry 的数组,其大小为 capacity(目前我们还不需要太了解该变量含义),那么 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.  

    final int hash;

  6.  

    ……

  7.  

    }

我们目前还是只着重核心的部分,Entry 是一个 static class,其中包含了 key 和 value,也就是键值对,另外还包含了一个 next 的 Entry 指针。我们可以总结出:Entry 就是数组中的元素,每个 Entry 其实就是一个 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.  

    //其允许存放null的key和null的value,当其key为null时,调用putForNullKey方法,放入到table[0]的这个位置

  15.  

    if (key == null)

  16.  

    return putForNullKey(value);

  17.  

    //通过调用hash方法对key进行哈希,得到哈希之后的数值。该方法实现可以通过看源码,其目的是为了尽可能的让键值对可以分不到不同的桶中

  18.  

    int hash = hash(key);

  19.  

    //根据上一步骤中求出的hash得到在数组中是索引i

  20.  

    int i = indexFor(hash, table.length);

  21.  

    //如果i处的Entry不为null,则通过其next指针不断遍历e元素的下一个元素。

  22.  

    for (Entry<K,V> e = table[i]; e != null; e = e.next) {

  23.  

    Object k;

  24.  

    if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {

  25.  

    V oldValue = e.value;

  26.  

    e.value = value;

  27.  

    e.recordAccess(this);

  28.  

    return oldValue;

  29.  

    }

  30.  

    }

  31.  

  32.  

    modCount++;

  33.  

    addEntry(hash, key, value, i);

  34.  

    return null;

  35.  

    }

我们看一下方法的标准注释:在注释中首先提到了,当我们 put 的时候,如果 key 存在了,那么新的 value 会代替旧的 value,并且如果 key 存在的情况下,该方法返回的是旧的 value,如果 key 不存在,那么返回 null。

从上面的源代码中可以看出:当我们往 HashMap 中 put 元素的时候,先根据 key 的 hashCode 重新计算 hash 值,根据 hash 值得到这个元素在数组中的位置(即下标),如果数组该位置上已经存放有其他元素了,那么在这个位置上的元素将以链表的形式存放,新加入的放在链头,最先加入的放在链尾。如果数组该位置上没有元素,就直接将该元素放到此数组中的该位置上。

addEntry(hash, key, value, i)方法根据计算出的 hash 值,将 key-value 对放在数组 table 的 i 索引处。addEntry 是 HashMap 提供的一个包访问权限的方法,代码如下:

  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.  

    }

  17.  

    void createEntry(int hash, K key, V value, int bucketIndex) {

  18.  

    // 获取指定 bucketIndex 索引处的 Entry

  19.  

    Entry<K,V> e = table[bucketIndex];

  20.  

    // 将新创建的 Entry 放入 bucketIndex 索引处,并让新的 Entry 指向原来的 Entr

  21.  

    table[bucketIndex] = new Entry<>(hash, key, value, e);

  22.  

    size++;

  23.  

    }

当系统决定存储 HashMap 中的 key-value 对时,完全没有考虑 Entry 中的 value,仅仅只是根据 key 来计算并决定每个 Entry 的存储位置。我们完全可以把 Map 集合中的 value 当成 key 的附属,当系统决定了 key 的存储位置之后,value 随之保存在那里即可。

hash(int h)方法根据 key 的 hashCode 重新计算一次散列。此算法加入了高位计算,防止低位不变,高位变化时,造成的 hash 冲突。

  1. final int hash(Object k) {

  2.  

    int h = 0;

  3.  

    if (useAltHashing) {

  4.  

    if (k instanceof String) {

  5.  

    return sun.misc.Hashing.stringHash32((String) k);

  6.  

    }

  7.  

    h = hashSeed;

  8.  

    }

  9.  

    //得到k的hashcode值

  10.  

    h ^= k.hashCode();

  11.  

    //进行计算

  12.  

    h ^= (h >>> 20) ^ (h >>> 12);

  13.  

    return h ^ (h >>> 7) ^ (h >>> 4);

  14.  

    }

我们可以看到在 HashMap 中要找到某个元素,需要根据 key 的 hash 值来求得对应数组中的位置。如何计算这个位置就是 hash 算法。前面说过 HashMap 的数据结构是数组和链表的结合,所以我们当然希望这个 HashMap 里面的 元素位置尽量的分布均匀些,尽量使得每个位置上的元素数量只有一个,那么当我们用 hash 算法求得这个位置的时候,马上就可以知道对应位置的元素就是我们要的,而不用再去遍历链表,这样就大大优化了查询的效率。

对于任意给定的对象,只要它的 hashCode() 返回值相同,那么程序调用 hash(int h) 方法所计算得到的 hash 码值总是相同的。我们首先想到的就是把 hash 值对数组长度取模运算,这样一来,元素的分布相对来说是比较均匀的。但是,“模”运算的消耗还是比较大的,在 HashMap 中是这样做的:调用 indexFor(int h, int length) 方法来计算该对象应该保存在 table 数组的哪个索引处。indexFor(int h, int length) 方法的代码如下:

  1. /**

  2.  

    * Returns index for hash code h.

  3.  

    */

  4.  

    static int indexFor(int h, int length) {

  5.  

    return h & (length-1);

  6.  

    }

这个方法非常巧妙,它通过 h & (table.length -1) 来得到该对象的保存位,而 HashMap 底层数组的长度总是 2 的 n 次方,这是 HashMap 在速度上的优化。在 HashMap 构造器中有如下代码:

  1. // Find a power of 2 >= initialCapacity

  2.  

    int capacity = 1;

  3.  

    while (capacity < initialCapacity)

  4.  

    capacity <<= 1;

这段代码保证初始化时 HashMap 的容量总是 2 的 n 次方,即底层数组的长度总是为 2 的 n 次方。

当 length 总是 2 的 n 次方时,h& (length-1)运算等价于对 length 取模,也就是 h%length,但是 & 比 % 具有更高的效率。这看上去很简单,其实比较有玄机的,我们举个例子来说明:

假设数组长度分别为 15 和 16,优化后的 hash 码分别为 8 和 9,那么 & 运算后的结果如下:

h & (table.length-1) hash   table.length-1  
8 & (15-1): 0100 & 1110 = 0100
9 & (15-1): 0101 & 1110 = 0100
8 & (16-1): 0100 & 1111 = 0100
9 & (16-1): 0101 & 1111 = 0101

从上面的例子中可以看出:当它们和 15-1(1110)“与”的时候,产生了相同的结果,也就是说它们会定位到数组中的同一个位置上去,这就产生了碰撞,8 和 9 会被放到数组中的同一个位置上形成链表,那么查询的时候就需要遍历这个链 表,得到8或者9,这样就降低了查询的效率。同时,我们也可以发现,当数组长度为 15 的时候,hash 值会与 15-1(1110)进行“与”,那么最后一位永远是 0,而 0001,0011,0101,1001,1011,0111,1101 这几个位置永远都不能存放元素了,空间浪费相当大,更糟的是这种情况中,数组可以使用的位置比数组长度小了很多,这意味着进一步增加了碰撞的几率,减慢了查询的效率!而当数组长度为16时,即为2的n次方时,2n-1 得到的二进制数的每个位上的值都为 1,这使得在低位上&时,得到的和原 hash 的低位相同,加之 hash(int h)方法对 key 的 hashCode 的进一步优化,加入了高位计算,就使得只有相同的 hash 值的两个值才会被放到数组中的同一个位置上形成链表。

所以说,当数组长度为 2 的 n 次幂的时候,不同的 key 算得得 index 相同的几率较小,那么数据在数组上分布就比较均匀,也就是说碰撞的几率小,相对的,查询的时候就不用遍历某个位置上的链表,这样查询效率也就较高了。

根据上面 put 方法的源代码可以看出,当程序试图将一个key-value对放入HashMap中时,程序首先根据该 key 的 hashCode() 返回值决定该 Entry 的存储位置:如果两个 Entry 的 key 的 hashCode() 返回值相同,那它们的存储位置相同。如果这两个 Entry 的 key 通过 equals 比较返回 true,新添加 Entry 的 value 将覆盖集合中原有 Entry 的 value,但key不会覆盖。如果这两个 Entry 的 key 通过 equals 比较返回 false,新添加的 Entry 将与集合中原有 Entry 形成 Entry 链,而且新添加的 Entry 位于 Entry 链的头部——具体说明继续看 addEntry() 方法的说明。

读取

  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.  

    * <p>A return value of {@code null} does not <i>necessarily</i>

  11.  

    * indicate that the map contains no mapping for the key; it‘s also

  12.  

    * possible that the map explicitly maps the key to {@code null}.

  13.  

    * The {@link #containsKey containsKey} operation may be used to

  14.  

    * distinguish these two cases.

  15.  

    *

  16.  

    * @see #put(Object, Object)

  17.  

    */

  18.  

    public V get(Object key) {

  19.  

    if (key == null)

  20.  

    return getForNullKey();

  21.  

    Entry<K,V> entry = getEntry(key);

  22.  

  23.  

    return null == entry ? null : entry.getValue();

  24.  

    }

  25.  

    final Entry<K,V> getEntry(Object key) {

  26.  

    int hash = (key == null) ? 0 : hash(key);

  27.  

    for (Entry<K,V> e = table[indexFor(hash, table.length)];

  28.  

    e != null;

  29.  

    e = e.next) {

  30.  

    Object k;

  31.  

    if (e.hash == hash &&

  32.  

    ((k = e.key) == key || (key != null && key.equals(k))))

  33.  

    return e;

  34.  

    }

  35.  

    return null;

  36.  

    }

有了上面存储时的 hash 算法作为基础,理解起来这段代码就很容易了。从上面的源代码中可以看出:从 HashMap 中 get 元素时,首先计算 key 的 hashCode,找到数组中对应位置的某一元素,然后通过 key 的 equals 方法在对应位置的链表中找到需要的元素。

归纳

简单地说,HashMap 在底层将 key-value 当成一个整体进行处理,这个整体就是一个 Entry 对象。HashMap 底层采用一个 Entry[] 数组来保存所有的 key-value 对,当需要存储一个 Entry 对象时,会根据 hash 算法来决定其在数组中的存储位置,在根据 equals 方法决定其在该数组位置上的链表中的存储位置;当需要取出一个Entry 时,也会根据 hash 算法找到其在数组中的存储位置,再根据 equals 方法从该位置上的链表中取出该Entry。

HashMap 的 resize(rehash)

当 HashMap 中的元素越来越多的时候,hash 冲突的几率也就越来越高,因为数组的长度是固定的。所以为了提高查询的效率,就要对 HashMap 的数组进行扩容,数组扩容这个操作也会出现在 ArrayList 中,这是一个常用的操作,而在 HashMap 数组扩容之后,最消耗性能的点就出现了:原数组中的数据必须重新计算其在新数组中的位置,并放进去,这就是 resize。

那么 HashMap 什么时候进行扩容呢?当 HashMap 中的元素个数超过数组大小 *loadFactor时,就会进行数组扩容,loadFactor的默认值为 0.75,这是一个折中的取值。也就是说,默认情况下,数组大小为 16,那么当 HashMap 中元素个数超过 16*0.75=12 的时候,就把数组的大小扩展为 2*16=32,即扩大一倍,然后重新计算每个元素在数组中的位置,而这是一个非常消耗性能的操作,所以如果我们已经预知 HashMap 中元素的个数,那么预设元素的个数能够有效的提高 HashMap 的性能。

HashMap 的性能参数

HashMap 包含如下几个构造器:

  • HashMap():构建一个初始容量为 16,负载因子为 0.75 的 HashMap。
  • ashMap(int initialCapacity):构建一个初始容量为 initialCapacity,负载因子为 0.75 的 HashMap。
  • HashMap(int initialCapacity, float loadFactor):以指定初始容量、指定的负载因子创建一个 HashMap。

HashMap 的基础构造器 HashMap(int initialCapacity, float loadFactor) 带有两个参数,它们是初始容量 initialCapacity 和负载因子 loadFactor。

负载因子 loadFactor 衡量的是一个散列表的空间的使用程度,负载因子越大表示散列表的装填程度越高,反之愈小。对于使用链表法的散列表来说,查找一个元素的平均时间是 O(1+a),因此如果负载因子越大,对空间的利用更充分,然而后果是查找效率的降低;如果负载因子太小,那么散列表的数据将过于稀疏,对空间造成严重浪费。

HashMap 的实现中,通过 threshold 字段来判断 HashMap 的最大容量:

        threshold = (int)(capacity * loadFactor);

结合负载因子的定义公式可知,threshold 就是在此 loadFactor 和 capacity 对应下允许的最大元素数目,超过这个数目就重新 resize,以降低实际的负载因子。默认的的负载因子 0.75 是对空间和时间效率的一个平衡选择。当容量超出此最大容量时, resize 后的 HashMap 容量是容量的两倍:

Fail-Fast 机制

原理

我们知道 java.util.HashMap 不是线程安全的,因此如果在使用迭代器的过程中有其他线程修改了 map,那么将抛出 ConcurrentModificationException,这就是所谓 fail-fast 策略。

ail-fast 机制是 java 集合(Collection)中的一种错误机制。 当多个线程对同一个集合的内容进行操作时,就可能会产生 fail-fast 事件。

例如:当某一个线程 A 通过 iterator去遍历某集合的过程中,若该集合的内容被其他线程所改变了;那么线程 A 访问集合时,就会抛出 ConcurrentModificationException 异常,产生 fail-fast 事件。

这一策略在源码中的实现是通过 modCount 域,modCount 顾名思义就是修改次数,对 HashMap 内容(当然不仅仅是 HashMap 才会有,其他例如 ArrayList 也会)的修改都将增加这个值(大家可以再回头看一下其源码,在很多操作中都有 modCount++ 这句),那么在迭代器初始化过程中会将这个值赋给迭代器的 expectedModCount。

  1. HashIterator() {

  2.  

    expectedModCount = modCount;

  3.  

    if (size > 0) { // advance to first entry

  4.  

    Entry[] t = table;

  5.  

    while (index < t.length && (next = t[index++]) == null)

  6.  

    ;

  7.  

    }

  8.  

    }

在迭代过程中,判断 modCount 跟 expectedModCount 是否相等,如果不相等就表示已经有其他线程修改了 Map:

注意到 modCount 声明为 volatile,保证线程之间修改的可见性。

  1. final Entry<K,V> nextEntry() {

  2.  

    if (modCount != expectedModCount)

  3.  

    throw new ConcurrentModificationException();

在 HashMap 的 API 中指出:

由所有 HashMap 类的“collection 视图方法”所返回的迭代器都是快速失败的:在迭代器创建之后,如果从结构上对映射进行修改,除非通过迭代器本身的 remove 方法,其他任何时间任何方式的修改,迭代器都将抛出 ConcurrentModificationException。因此,面对并发的修改,迭代器很快就会完全失败,而不冒在将来不确定的时间发生任意不确定行为的风险。

注意,迭代器的快速失败行为不能得到保证,一般来说,存在非同步的并发修改时,不可能作出任何坚决的保证。快速失败迭代器尽最大努力抛出 ConcurrentModificationException。因此,编写依赖于此异常的程序的做法是错误的,正确做法是:迭代器的快速失败行为应该仅用于检测程序错误。

解决方案

在上文中也提到,fail-fast 机制,是一种错误检测机制。它只能被用来检测错误,因为 JDK 并不保证 fail-fast 机制一定会发生。若在多线程环境下使用 fail-fast 机制的集合,建议使用“java.util.concurrent 包下的类”去取代“java.util 包下的类”。

HashMap 的两种遍历方式

第一种

  1.   Map map = new HashMap();

  2.  

      Iterator iter = map.entrySet().iterator();

  3.  

      while (iter.hasNext()) {

  4.  

      Map.Entry entry = (Map.Entry) iter.next();

  5.  

      Object key = entry.getKey();

  6.  

      Object val = entry.getValue();

  7.  

      }

效率高,以后一定要使用此种方式!

第二种

  1.   Map map = new HashMap();

  2.  

      Iterator iter = map.keySet().iterator();

  3.  

      while (iter.hasNext()) {

  4.  

      Object key = iter.next();

  5.  

      Object val = map.get(key);

  6.  

      }

效率低,以后尽量少使用!

HashSet 的实现原理

HashSet 概述

对于 HashSet 而言,它是基于 HashMap 实现的,底层采用 HashMap 来保存元素,所以如果对 HashMap 比较熟悉了,那么学习 HashSet 也是很轻松的。

我们先通过 HashSet 最简单的构造函数和几个成员变量来看一下,证明咱们上边说的,其底层是 HashMap:

  1. private transient HashMap<E,Object> map;

  2.  

  3.  

    // Dummy value to associate with an Object in the backing Map

  4.  

    private static final Object PRESENT = new Object();

  5.  

  6.  

    /**

  7.  

    * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has

  8.  

    * default initial capacity (16) and load factor (0.75).

  9.  

    */

  10.  

    public HashSet() {

  11.  

    map = new HashMap<>();

  12.  

    }

其实在英文注释中已经说的比较明确了。首先有一个HashMap的成员变量,我们在 HashSet 的构造函数中将其初始化,默认情况下采用的是 initial capacity为16,load factor 为 0.75。

HashSet 的实现

对于 HashSet 而言,它是基于 HashMap 实现的,HashSet 底层使用 HashMap 来保存所有元素,因此 HashSet 的实现比较简单,相关 HashSet 的操作,基本上都是直接调用底层 HashMap 的相关方法来完成,我们应该为保存到 HashSet 中的对象覆盖 hashCode() 和 equals()

构造方法

  1. /**

  2.  

    * 默认的无参构造器,构造一个空的HashSet。

  3.  

    *

  4.  

    * 实际底层会初始化一个空的HashMap,并使用默认初始容量为16和加载因子0.75。

  5.  

    */

  6.  

    public HashSet() {

  7.  

    map = new HashMap<E,Object>();

  8.  

    }

  9.  

  10.  

    /**

  11.  

    * 构造一个包含指定collection中的元素的新set。

  12.  

    *

  13.  

    * 实际底层使用默认的加载因子0.75和足以包含指定collection中所有元素的初始容量来创建一个HashMap。

  14.  

    * @param c 其中的元素将存放在此set中的collection。

  15.  

    */

  16.  

    public HashSet(Collection<? extends E> c) {

  17.  

    map = new HashMap<E,Object>(Math.max((int) (c.size()/.75f) + 1, 16));

  18.  

    addAll(c);

  19.  

    }

  20.  

  21.  

    /**

  22.  

    * 以指定的initialCapacity和loadFactor构造一个空的HashSet。

  23.  

    *

  24.  

    * 实际底层以相应的参数构造一个空的HashMap。

  25.  

    * @param initialCapacity 初始容量。

  26.  

    * @param loadFactor 加载因子。

  27.  

    */

  28.  

    public HashSet(int initialCapacity, float loadFactor) {

  29.  

    map = new HashMap<E,Object>(initialCapacity, loadFactor);

  30.  

    }

  31.  

  32.  

    /**

  33.  

    * 以指定的initialCapacity构造一个空的HashSet。

  34.  

    *

  35.  

    * 实际底层以相应的参数及加载因子loadFactor为0.75构造一个空的HashMap。

  36.  

    * @param initialCapacity 初始容量。

  37.  

    */

  38.  

    public HashSet(int initialCapacity) {

  39.  

    map = new HashMap<E,Object>(initialCapacity);

  40.  

    }

  41.  

  42.  

    /**

  43.  

    * 以指定的initialCapacity和loadFactor构造一个新的空链接哈希集合。此构造函数为包访问权限,不对外公开,

  44.  

    * 实际只是是对LinkedHashSet的支持。

  45.  

    *

  46.  

    * 实际底层会以指定的参数构造一个空LinkedHashMap实例来实现。

  47.  

    * @param initialCapacity 初始容量。

  48.  

    * @param loadFactor 加载因子。

  49.  

    * @param dummy 标记。

  50.  

    */

  51.  

    HashSet(int initialCapacity, float loadFactor, boolean dummy) {

  52.  

    map = new LinkedHashMap<E,Object>(initialCapacity, loadFactor);

  53.  

    }

add 方法

  1. /**

  2.  

  3.  

    * @param e 将添加到此set中的元素。

  4.  

    * @return 如果此set尚未包含指定元素,则返回true。

  5.  

    */

  6.  

    public boolean add(E e) {

  7.  

    return map.put(e, PRESENT)==null;

  8.  

    }

如果此 set 中尚未包含指定元素,则添加指定元素。更确切地讲,如果此 set 没有包含满足(e==null ? e2==null : e.equals(e2)) 的元素 e2,则向此 set 添加指定的元素 e。如果此 set 已包含该元素,则该调用不更改 set 并返回 false。但底层实际将将该元素作为 key 放入 HashMap。思考一下为什么?

由于 HashMap 的 put() 方法添加 key-value 对时,当新放入 HashMap 的 Entry 中 key 与集合中原有 Entry 的 key 相同(hashCode()返回值相等,通过 equals 比较也返回 true),新添加的 Entry 的 value 会将覆盖原来 Entry 的 value(HashSet 中的 value 都是PRESENT),但 key 不会有任何改变,因此如果向 HashSet 中添加一个已经存在的元素时,新添加的集合元素将不会被放入 HashMap中,原来的元素也不会有任何改变,这也就满足了 Set 中元素不重复的特性。

该方法如果添加的是在 HashSet 中不存在的,则返回 true;如果添加的元素已经存在,返回 false。其原因在于我们之前提到的关于 HashMap 的 put 方法。该方法在添加 key 不重复的键值对的时候,会返回 null。

其余方法

  1. /**

  2.  

    * 如果此set包含指定元素,则返回true。

  3.  

    * 更确切地讲,当且仅当此set包含一个满足(o==null ? e==null : o.equals(e))的e元素时,返回true。

  4.  

    *

  5.  

    * 底层实际调用HashMap的containsKey判断是否包含指定key。

  6.  

    * @param o 在此set中的存在已得到测试的元素。

  7.  

    * @return 如果此set包含指定元素,则返回true。

  8.  

    */

  9.  

    public boolean contains(Object o) {

  10.  

    return map.containsKey(o);

  11.  

    }

  12.  

    /**

  13.  

    * 如果指定元素存在于此set中,则将其移除。更确切地讲,如果此set包含一个满足(o==null ? e==null : o.equals(e))的元素e,

  14.  

    * 则将其移除。如果此set已包含该元素,则返回true

  15.  

    *

  16.  

    * 底层实际调用HashMap的remove方法删除指定Entry。

  17.  

    * @param o 如果存在于此set中则需要将其移除的对象。

  18.  

    * @return 如果set包含指定元素,则返回true。

  19.  

    */

  20.  

    public boolean remove(Object o) {

  21.  

    return map.remove(o)==PRESENT;

  22.  

    }

  23.  

    /**

  24.  

    * 返回此HashSet实例的浅表副本:并没有复制这些元素本身。

  25.  

    *

  26.  

    * 底层实际调用HashMap的clone()方法,获取HashMap的浅表副本,并设置到HashSet中。

  27.  

    */

  28.  

    public Object clone() {

  29.  

    try {

  30.  

    HashSet<E> newSet = (HashSet<E>) super.clone();

  31.  

    newSet.map = (HashMap<E, Object>) map.clone();

  32.  

    return newSet;

  33.  

    } catch (CloneNotSupportedException e) {

  34.  

    throw new InternalError();

  35.  

    }

  36.  

    }

  37.  

    }

相关说明

  1. 相关 HashMap 的实现原理,请参考我的上一遍总结:HashMap的实现原理
  2. 对于 HashSet 中保存的对象,请注意正确重写其 equals 和 hashCode 方法,以保证放入的对象的唯一性。这两个方法是比较重要的,希望大家在以后的开发过程中需要注意一下。

Hashtable 的实现原理

概述

和 HashMap 一样,Hashtable 也是一个散列表,它存储的内容是键值对。

Hashtable 在 Java 中的定义为:

  1. public class Hashtable<K,V>

  2.  

    extends Dictionary<K,V>

  3.  

    implements Map<K,V>, Cloneable, java.io.Serializable{}

从源码中,我们可以看出,Hashtable 继承于 Dictionary 类,实现了 Map, Cloneable, java.io.Serializable接口。其中Dictionary类是任何可将键映射到相应值的类(如 Hashtable)的抽象父类,每个键和值都是对象(源码注释为:The Dictionary class is the abstract parent of any class, such as Hashtable, which maps keys to values. Every key and every value is an object.)。但在这一点我开始有点怀疑,因为我查看了HashMap以及TreeMap的源码,都没有继承于这个类。不过当我看到注释中的解释也就明白了,其 Dictionary 源码注释是这样的:NOTE: This class is obsolete. New implementations should implement the Map interface, rather than extending this class. 该话指出 Dictionary 这个类过时了,新的实现类应该实现Map接口。

Hashtable 源码解读

成员变量

Hashtable是通过"拉链法"实现的哈希表。它包括几个重要的成员变量:table, count, threshold, loadFactor, modCount。

  • table是一个 Entry[] 数组类型,而 Entry(在 HashMap 中有讲解过)实际上就是一个单向链表。哈希表的"key-value键值对"都是存储在Entry数组中的。
  • count 是 Hashtable 的大小,它是 Hashtable 保存的键值对的数量。
  • threshold 是 Hashtable 的阈值,用于判断是否需要调整 Hashtable 的容量。threshold 的值="容量*加载因子"。
  • loadFactor 就是加载因子。
  • modCount 是用来实现 fail-fast 机制的。

关于变量的解释在源码注释中都有,最好还是应该看英文注释。

  1. /**

  2.  

    * The hash table data.

  3.  

    */

  4.  

    private transient Entry<K,V>[] table;

  5.  

  6.  

    /**

  7.  

    * The total number of entries in the hash table.

  8.  

    */

  9.  

    private transient int count;

  10.  

  11.  

    /**

  12.  

    * The table is rehashed when its size exceeds this threshold. (The

  13.  

    * value of this field is (int)(capacity * loadFactor).)

  14.  

    *

  15.  

    * @serial

  16.  

    */

  17.  

    private int threshold;

  18.  

  19.  

    /**

  20.  

    * The load factor for the hashtable.

  21.  

    *

  22.  

    * @serial

  23.  

    */

  24.  

    private float loadFactor;

  25.  

  26.  

    /**

  27.  

    * The number of times this Hashtable has been structurally modified

  28.  

    * Structural modifications are those that change the number of entries in

  29.  

    * the Hashtable or otherwise modify its internal structure (e.g.,

  30.  

    * rehash). This field is used to make iterators on Collection-views of

  31.  

    * the Hashtable fail-fast. (See ConcurrentModificationException).

  32.  

    */

  33.  

    private transient int modCount = 0;

构造方法

Hashtable 一共提供了 4 个构造方法:

  • public Hashtable(int initialCapacity, float loadFactor): 用指定初始容量和指定加载因子构造一个新的空哈希表。useAltHashing 为 boolean,其如果为真,则执行另一散列的字符串键,以减少由于弱哈希计算导致的哈希冲突的发生。
  • public Hashtable(int initialCapacity):用指定初始容量和默认的加载因子 (0.75) 构造一个新的空哈希表。
  • public Hashtable():默认构造函数,容量为 11,加载因子为 0.75。
  • public Hashtable(Map<? extends K, ? extends V> t):构造一个与给定的 Map 具有相同映射关系的新哈希表。
  1. /**

  2.  

    * Constructs a new, empty hashtable with the specified initial

  3.  

    * capacity and the specified load factor.

  4.  

    *

  5.  

    * @param initialCapacity the initial capacity of the hashtable.

  6.  

    * @param loadFactor the load factor of the hashtable.

  7.  

    * @exception IllegalArgumentException if the initial capacity is less

  8.  

    * than zero, or if the load factor is nonpositive.

  9.  

    */

  10.  

    public Hashtable(int initialCapacity, float loadFactor) {

  11.  

    if (initialCapacity < 0)

  12.  

    throw new IllegalArgumentException("Illegal Capacity: "+

  13.  

    initialCapacity);

  14.  

    if (loadFactor <= 0 || Float.isNaN(loadFactor))

  15.  

    throw new IllegalArgumentException("Illegal Load: "+loadFactor);

  16.  

  17.  

    if (initialCapacity==0)

  18.  

    initialCapacity = 1;

  19.  

    this.loadFactor = loadFactor;

  20.  

    table = new Entry[initialCapacity];

  21.  

    threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);

  22.  

    useAltHashing = sun.misc.VM.isBooted() &&

  23.  

    (initialCapacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);

  24.  

    }

  25.  

  26.  

    /**

  27.  

    * Constructs a new, empty hashtable with the specified initial capacity

  28.  

    * and default load factor (0.75).

  29.  

    *

  30.  

    * @param initialCapacity the initial capacity of the hashtable.

  31.  

    * @exception IllegalArgumentException if the initial capacity is less

  32.  

    * than zero.

  33.  

    */

  34.  

    public Hashtable(int initialCapacity) {

  35.  

    this(initialCapacity, 0.75f);

  36.  

    }

  37.  

  38.  

    /**

  39.  

    * Constructs a new, empty hashtable with a default initial capacity (11)

  40.  

    * and load factor (0.75).

  41.  

    */

  42.  

    public Hashtable() {

  43.  

    this(11, 0.75f);

  44.  

    }

  45.  

  46.  

    /**

  47.  

    * Constructs a new hashtable with the same mappings as the given

  48.  

    * Map. The hashtable is created with an initial capacity sufficient to

  49.  

    * hold the mappings in the given Map and a default load factor (0.75).

  50.  

    *

  51.  

    * @param t the map whose mappings are to be placed in this map.

  52.  

    * @throws NullPointerException if the specified map is null.

  53.  

    * @since 1.2

  54.  

    */

  55.  

    public Hashtable(Map<? extends K, ? extends V> t) {

  56.  

    this(Math.max(2*t.size(), 11), 0.75f);

  57.  

    putAll(t);

  58.  

    }

put 方法

put 方法的整个流程为:

  1. 判断 value 是否为空,为空则抛出异常;
  2. 计算 key 的 hash 值,并根据 hash 值获得 key 在 table 数组中的位置 index,如果 table[index] 元素不为空,则进行迭代,如果遇到相同的 key,则直接替换,并返回旧 value;
  3. 否则,我们可以将其插入到 table[index] 位置。

我在下面的代码中也进行了一些注释:

  1. public synchronized V put(K key, V value) {

  2.  

    // Make sure the value is not null确保value不为null

  3.  

    if (value == null) {

  4.  

    throw new NullPointerException();

  5.  

    }

  6.  

  7.  

    // Makes sure the key is not already in the hashtable.

  8.  

    //确保key不在hashtable中

  9.  

    //首先,通过hash方法计算key的哈希值,并计算得出index值,确定其在table[]中的位置

  10.  

    //其次,迭代index索引位置的链表,如果该位置处的链表存在相同的key,则替换value,返回旧的value

  11.  

    Entry tab[] = table;

  12.  

    int hash = hash(key);

  13.  

    int index = (hash & 0x7FFFFFFF) % tab.length;

  14.  

    for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {

  15.  

    if ((e.hash == hash) && e.key.equals(key)) {

  16.  

    V old = e.value;

  17.  

    e.value = value;

  18.  

    return old;

  19.  

    }

  20.  

    }

  21.  

  22.  

    modCount++;

  23.  

    if (count >= threshold) {

  24.  

    // Rehash the table if the threshold is exceeded

  25.  

    //如果超过阀值,就进行rehash操作

  26.  

    rehash();

  27.  

  28.  

    tab = table;

  29.  

    hash = hash(key);

  30.  

    index = (hash & 0x7FFFFFFF) % tab.length;

  31.  

    }

  32.  

  33.  

    // Creates the new entry.

  34.  

    //将值插入,返回的为null

  35.  

    Entry<K,V> e = tab[index];

  36.  

    // 创建新的Entry节点,并将新的Entry插入Hashtable的index位置,并设置e为新的Entry的下一个元素

  37.  

    tab[index] = new Entry<>(hash, key, value, e);

  38.  

    count++;

  39.  

    return null;

  40.  

    }

通过一个实际的例子来演示一下这个过程:

假设我们现在Hashtable的容量为5,已经存在了(5,5),(13,13),(16,16),(17,17),(21,21)这 5 个键值对,目前他们在Hashtable中的位置如下:

现在,我们插入一个新的键值对,put(16,22),假设key=16的索引为1.但现在索引1的位置有两个Entry了,所以程序会对链表进行迭代。迭代的过程中,发现其中有一个Entry的key和我们要插入的键值对的key相同,所以现在会做的工作就是将newValue=22替换oldValue=16,然后返回oldValue=16.

然后我们现在再插入一个,put(33,33),key=33的索引为3,并且在链表中也不存在key=33的Entry,所以将该节点插入链表的第一个位置。

get 方法

相比较于 put 方法,get 方法则简单很多。其过程就是首先通过 hash()方法求得 key 的哈希值,然后根据 hash 值得到 index 索引(上述两步所用的算法与 put 方法都相同)。然后迭代链表,返回匹配的 key 的对应的 value;找不到则返回 null。

  1. public synchronized V get(Object key) {

  2.  

    Entry tab[] = table;

  3.  

    int hash = hash(key);

  4.  

    int index = (hash & 0x7FFFFFFF) % tab.length;

  5.  

    for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {

  6.  

    if ((e.hash == hash) && e.key.equals(key)) {

  7.  

    return e.value;

  8.  

    }

  9.  

    }

  10.  

    return null;

  11.  

    }

Hashtable 遍历方式

Hashtable 有多种遍历方式:

  1. //1、使用keys()

  2.  

    Enumeration<String> en1 = table.keys();

  3.  

    while(en1.hasMoreElements()) {

  4.  

    en1.nextElement();

  5.  

    }

  6.  

  7.  

    //2、使用elements()

  8.  

    Enumeration<String> en2 = table.elements();

  9.  

    while(en2.hasMoreElements()) {

  10.  

    en2.nextElement();

  11.  

    }

  12.  

  13.  

    //3、使用keySet()

  14.  

    Iterator<String> it1 = table.keySet().iterator();

  15.  

    while(it1.hasNext()) {

  16.  

    it1.next();

  17.  

    }

  18.  

  19.  

    //4、使用entrySet()

  20.  

    Iterator<Entry<String, String>> it2 = table.entrySet().iterator();

  21.  

    while(it2.hasNext()) {

  22.  

    it2.next();

  23.  

    }

Hashtable 与 HashMap 的简单比较

  1. HashTable 基于 Dictionary 类,而 HashMap 是基于 AbstractMap。Dictionary 是任何可将键映射到相应值的类的抽象父类,而 AbstractMap 是基于 Map 接口的实现,它以最大限度地减少实现此接口所需的工作。
  2. HashMap 的 key 和 value 都允许为 null,而 Hashtable 的 key 和 value 都不允许为 null。HashMap 遇到 key 为 null 的时候,调用 putForNullKey 方法进行处理,而对 value 没有处理;Hashtable遇到 null,直接返回 NullPointerException。
  3. Hashtable 方法是同步,而HashMap则不是。我们可以看一下源码,Hashtable 中的几乎所有的 public 的方法都是 synchronized 的,而有些方法也是在内部通过 synchronized 代码块来实现。所以有人一般都建议如果是涉及到多线程同步时采用 HashTable,没有涉及就采用 HashMap,但是在 Collections 类中存在一个静态方法:synchronizedMap(),该方法创建了一个线程安全的 Map 对象,并把它作为一个封装的对象来返回。

LinkedHashMap 的实现原理

LinkedHashMap 概述

HashMap 是无序的,HashMap 在 put 的时候是根据 key 的 hashcode 进行 hash 然后放入对应的地方。所以在按照一定顺序 put 进 HashMap 中,然后遍历出 HashMap 的顺序跟 put 的顺序不同(除非在 put 的时候 key 已经按照 hashcode 排序号了,这种几率非常小)

JAVA 在 JDK1.4 以后提供了 LinkedHashMap 来帮助我们实现了有序的 HashMap!

LinkedHashMap 是 HashMap 的一个子类,它保留插入的顺序,如果需要输出的顺序和输入时的相同,那么就选用 LinkedHashMap。

LinkedHashMap 是 Map 接口的哈希表和链接列表实现,具有可预知的迭代顺序。此实现提供所有可选的映射操作,并允许使用 null 值和 null 键。此类不保证映射的顺序,特别是它不保证该顺序恒久不变。

LinkedHashMap 实现与 HashMap 的不同之处在于,LinkedHashMap 维护着一个运行于所有条目的双重链接列表。此链接列表定义了迭代顺序,该迭代顺序可以是插入顺序或者是访问顺序。

注意,此实现不是同步的。如果多个线程同时访问链接的哈希映射,而其中至少一个线程从结构上修改了该映射,则它必须保持外部同步。

根据链表中元素的顺序可以分为:按插入顺序的链表,和按访问顺序(调用 get 方法)的链表。默认是按插入顺序排序,如果指定按访问顺序排序,那么调用get方法后,会将这次访问的元素移至链表尾部,不断访问可以形成按访问顺序排序的链表。

小 Demo

我在最开始学习 LinkedHashMap 的时候,看到访问顺序、插入顺序等等,有点晕了,随着后续的学习才慢慢懂得其中原理,所以我会先在进行做几个 demo 来演示一下 LinkedHashMap 的使用。看懂了其效果,然后再来研究其原理。

HashMap

看下面这个代码:

  1. public static void main(String[] args) {

  2.  

    Map<String, String> map = new HashMap<String, String>();

  3.  

    map.put("apple", "苹果");

  4.  

    map.put("watermelon", "西瓜");

  5.  

    map.put("banana", "香蕉");

  6.  

    map.put("peach", "桃子");

  7.  

  8.  

    Iterator iter = map.entrySet().iterator();

  9.  

    while (iter.hasNext()) {

  10.  

    Map.Entry entry = (Map.Entry) iter.next();

  11.  

    System.out.println(entry.getKey() + "=" + entry.getValue());

  12.  

    }

  13.  

    }

一个比较简单的测试 HashMap 的代码,通过控制台的输出,我们可以看到 HashMap 是没有顺序的。

  1. banana=香蕉

  2.  

    apple=苹果

  3.  

    peach=桃子

  4.  

    watermelon=西瓜

LinkedHashMap

我们现在将 map 的实现换成 LinkedHashMap,其他代码不变:Map<String, String> map = new LinkedHashMap<String, String>();

看一下控制台的输出:

  1. apple=苹果

  2.  

    watermelon=西瓜

  3.  

    banana=香蕉

  4.  

    peach=桃子

我们可以看到,其输出顺序是完成按照插入顺序的!也就是我们上面所说的保留了插入的顺序。我们不是在上面还提到过其可以按照访问顺序进行排序么?好的,我们还是通过一个例子来验证一下:

  1. public static void main(String[] args) {

  2.  

    Map<String, String> map = new LinkedHashMap<String, String>(16,0.75f,true);

  3.  

    map.put("apple", "苹果");

  4.  

    map.put("watermelon", "西瓜");

  5.  

    map.put("banana", "香蕉");

  6.  

    map.put("peach", "桃子");

  7.  

  8.  

    map.get("banana");

  9.  

    map.get("apple");

  10.  

  11.  

    Iterator iter = map.entrySet().iterator();

  12.  

    while (iter.hasNext()) {

  13.  

    Map.Entry entry = (Map.Entry) iter.next();

  14.  

    System.out.println(entry.getKey() + "=" + entry.getValue());

  15.  

    }

  16.  

    }

代码与之前的都差不多,但我们多了两行代码,并且初始化 LinkedHashMap 的时候,用的构造函数也不相同,看一下控制台的输出结果:

  1. watermelon=西瓜

  2.  

    peach=桃子

  3.  

    banana=香蕉

  4.  

    apple=苹果

这也就是我们之前提到过的,LinkedHashMap 可以选择按照访问顺序进行排序。

LinkedHashMap 的实现

对于 LinkedHashMap 而言,它继承与 HashMap(public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>)、底层使用哈希表与双向链表来保存所有元素。其基本操作与父类 HashMap 相似,它通过重写父类相关的方法,来实现自己的链接列表特性。下面我们来分析 LinkedHashMap 的源代码:

成员变量

LinkedHashMap 采用的 hash 算法和 HashMap 相同,但是它重新定义了数组中保存的元素 Entry,该 Entry 除了保存当前对象的引用外,还保存了其上一个元素 before 和下一个元素 after 的引用,从而在哈希表的基础上又构成了双向链接列表。看源代码:

  1. /**

  2.  

    * The iteration ordering method for this linked hash map: <tt>true</tt>

  3.  

    * for access-order, <tt>false</tt> for insertion-order.

  4.  

    * 如果为true,则按照访问顺序;如果为false,则按照插入顺序。

  5.  

    */

  6.  

    private final boolean accessOrder;

  7.  

    /**

  8.  

    * 双向链表的表头元素。

  9.  

    */

  10.  

    private transient Entry<K,V> header;

  11.  

  12.  

    /**

  13.  

    * LinkedHashMap的Entry元素。

  14.  

    * 继承HashMap的Entry元素,又保存了其上一个元素before和下一个元素after的引用。

  15.  

    */

  16.  

    private static class Entry<K,V> extends HashMap.Entry<K,V> {

  17.  

    Entry<K,V> before, after;

  18.  

    ……

  19.  

    }

LinkedHashMap 中的 Entry 集成与 HashMap 的 Entry,但是其增加了 before 和 after 的引用,指的是上一个元素和下一个元素的引用。

初始化

通过源代码可以看出,在 LinkedHashMap 的构造方法中,实际调用了父类 HashMap 的相关构造方法来构造一个底层存放的 table 数组,但额外可以增加 accessOrder 这个参数,如果不设置,默认为 false,代表按照插入顺序进行迭代;当然可以显式设置为 true,代表以访问顺序进行迭代。如:

  1. public LinkedHashMap(int initialCapacity, float loadFactor,boolean accessOrder) {

  2.  

    super(initialCapacity, loadFactor);

  3.  

    this.accessOrder = accessOrder;

  4.  

    }

我们已经知道 LinkedHashMap 的 Entry 元素继承 HashMap 的 Entry,提供了双向链表的功能。在上述 HashMap 的构造器中,最后会调用 init() 方法,进行相关的初始化,这个方法在 HashMap 的实现中并无意义,只是提供给子类实现相关的初始化调用。

但在 LinkedHashMap 重写了 init() 方法,在调用父类的构造方法完成构造后,进一步实现了对其元素 Entry 的初始化操作。

  1. /**

  2.  

    * Called by superclass constructors and pseudoconstructors (clone,

  3.  

    * readObject) before any entries are inserted into the map. Initializes

  4.  

    * the chain.

  5.  

    */

  6.  

    @Override

  7.  

    void init() {

  8.  

    header = new Entry<>(-1, null, null, null);

  9.  

    header.before = header.after = header;

  10.  

    }

存储

LinkedHashMap 并未重写父类 HashMap 的 put 方法,而是重写了父类 HashMap 的 put 方法调用的子方法void recordAccess(HashMap m) ,void addEntry(int hash, K key, V value, int bucketIndex) 和void createEntry(int hash, K key, V value, int bucketIndex),提供了自己特有的双向链接列表的实现。我们在之前的文章中已经讲解了HashMap的put方法,我们在这里重新贴一下 HashMap 的 put 方法的源代码:

HashMap.put:

  1. public V put(K key, V value) {

  2.  

    if (key == null)

  3.  

    return putForNullKey(value);

  4.  

    int hash = hash(key);

  5.  

    int i = indexFor(hash, table.length);

  6.  

    for (Entry<K,V> e = table[i]; e != null; e = e.next) {

  7.  

    Object k;

  8.  

    if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {

  9.  

    V oldValue = e.value;

  10.  

    e.value = value;

  11.  

    e.recordAccess(this);

  12.  

    return oldValue;

  13.  

    }

  14.  

    }

  15.  

  16.  

    modCount++;

  17.  

    addEntry(hash, key, value, i);

  18.  

    return null;

  19.  

    }

重写方法:

  1. void recordAccess(HashMap<K,V> m) {

  2.  

    LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m;

  3.  

    if (lm.accessOrder) {

  4.  

    lm.modCount++;

  5.  

    remove();

  6.  

    addBefore(lm.header);

  7.  

    }

  8.  

    }

  9.  

  10.  

    void addEntry(int hash, K key, V value, int bucketIndex) {

  11.  

    // 调用create方法,将新元素以双向链表的的形式加入到映射中。

  12.  

    createEntry(hash, key, value, bucketIndex);

  13.  

  14.  

    // 删除最近最少使用元素的策略定义

  15.  

    Entry<K,V> eldest = header.after;

  16.  

    if (removeEldestEntry(eldest)) {

  17.  

    removeEntryForKey(eldest.key);

  18.  

    } else {

  19.  

    if (size >= threshold)

  20.  

    resize(2 * table.length);

  21.  

    }

  22.  

    }

  23.  

  24.  

    void createEntry(int hash, K key, V value, int bucketIndex) {

  25.  

    HashMap.Entry<K,V> old = table[bucketIndex];

  26.  

    Entry<K,V> e = new Entry<K,V>(hash, key, value, old);

  27.  

    table[bucketIndex] = e;

  28.  

    // 调用元素的addBrefore方法,将元素加入到哈希、双向链接列表。

  29.  

    e.addBefore(header);

  30.  

    size++;

  31.  

    }

  32.  

  33.  

    private void addBefore(Entry<K,V> existingEntry) {

  34.  

    after = existingEntry;

  35.  

    before = existingEntry.before;

  36.  

    before.after = this;

  37.  

    after.before = this;

  38.  

    }

读取

LinkedHashMap 重写了父类 HashMap 的 get 方法,实际在调用父类 getEntry() 方法取得查找的元素后,再判断当排序模式 accessOrder 为 true 时,记录访问顺序,将最新访问的元素添加到双向链表的表头,并从原来的位置删除。由于的链表的增加、删除操作是常量级的,故并不会带来性能的损失。

  1. public V get(Object key) {

  2.  

    // 调用父类HashMap的getEntry()方法,取得要查找的元素。

  3.  

    Entry<K,V> e = (Entry<K,V>)getEntry(key);

  4.  

    if (e == null)

  5.  

    return null;

  6.  

    // 记录访问顺序。

  7.  

    e.recordAccess(this);

  8.  

    return e.value;

  9.  

    }

  10.  

  11.  

    void recordAccess(HashMap<K,V> m) {

  12.  

    LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m;

  13.  

    // 如果定义了LinkedHashMap的迭代顺序为访问顺序,

  14.  

    // 则删除以前位置上的元素,并将最新访问的元素添加到链表表头。

  15.  

    if (lm.accessOrder) {

  16.  

    lm.modCount++;

  17.  

    remove();

  18.  

    addBefore(lm.header);

  19.  

    }

  20.  

    }

  21.  

  22.  

    /**

  23.  

    * Removes this entry from the linked list.

  24.  

    */

  25.  

    private void remove() {

  26.  

    before.after = after;

  27.  

    after.before = before;

  28.  

    }

  29.  

  30.  

    /**clear链表,设置header为初始状态*/

  31.  

    public void clear() {

  32.  

    super.clear();

  33.  

    header.before = header.after = header;

  34.  

    }

排序模式

LinkedHashMap 定义了排序模式 accessOrder,该属性为 boolean 型变量,对于访问顺序,为 true;对于插入顺序,则为 false。一般情况下,不必指定排序模式,其迭代顺序即为默认为插入顺序。

这些构造方法都会默认指定排序模式为插入顺序。如果你想构造一个 LinkedHashMap,并打算按从近期访问最少到近期访问最多的顺序(即访问顺序)来保存元素,那么请使用下面的构造方法构造 LinkedHashMap:public LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)

该哈希映射的迭代顺序就是最后访问其条目的顺序,这种映射很适合构建 LRU 缓存。LinkedHashMap 提供了 removeEldestEntry(Map.Entry<K,V> eldest) 方法。该方法可以提供在每次添加新条目时移除最旧条目的实现程序,默认返回 false,这样,此映射的行为将类似于正常映射,即永远不能移除最旧的元素。

我们会在后面的文章中详细介绍关于如何用 LinkedHashMap 构建 LRU 缓存。

总结

其实 LinkedHashMap 几乎和 HashMap 一样:从技术上来说,不同的是它定义了一个 Entry<K,V> header,这个 header 不是放在 Table 里,它是额外独立出来的。LinkedHashMap 通过继承 hashMap 中的 Entry<K,V>,并添加两个属性 Entry<K,V> before,after,和 header 结合起来组成一个双向链表,来实现按插入顺序或访问顺序排序。

在写关于 LinkedHashMap 的过程中,记起来之前面试的过程中遇到的一个问题,也是问我 Map 的哪种实现可以做到按照插入顺序进行迭代?当时脑子是突然短路的,但现在想想,也只能怪自己对这个知识点还是掌握的不够扎实,所以又从头认真的把代码看了一遍。

不过,我的建议是,大家首先首先需要记住的是:LinkedHashMap 能够做到按照插入顺序或者访问顺序进行迭代,这样在我们以后的开发中遇到相似的问题,才能想到用 LinkedHashMap 来解决,否则就算对其内部结构非常了解,不去使用也是没有什么用的。

LinkedHashSet 的实现原理

LinkedHashSet 概述

思考了好久,到底要不要总结 LinkedHashSet 的内容 = = 我在之前的博文中,分别写了 HashMap 和 HashSet,然后我们可以看到 HashSet 的方法基本上都是基于 HashMap 来实现的,说白了,HashSet内部的数据结构就是一个 HashMap,其方法的内部几乎就是在调用 HashMap 的方法。

LinkedHashSet 首先我们需要知道的是它是一个 Set 的实现,所以它其中存的肯定不是键值对,而是值。此实现与 HashSet 的不同之处在于,LinkedHashSet 维护着一个运行于所有条目的双重链接列表。此链接列表定义了迭代顺序,该迭代顺序可为插入顺序或是访问顺序。

看到上面的介绍,是不是感觉其与 HashMap 和 LinkedHashMap 的关系很像?

注意,此实现不是同步的。如果多个线程同时访问链接的哈希Set,而其中至少一个线程修改了该 Set,则它必须保持外部同步。

小 Demo

LinkedHashMap的实现原理中,通过例子演示了 HashMap 和 LinkedHashMap 的区别。举一反三,我们现在学习的LinkedHashSet与之前的很相同,只不过之前存的是键值对,而现在存的只有值。

所以我就不再具体的贴代码在这边了,但我们可以肯定的是,LinkedHashSet 是可以按照插入顺序或者访问顺序进行迭代。

LinkedHashSet 的实现

对于 LinkedHashSet 而言,它继承与 HashSet、又基于 LinkedHashMap 来实现的。

LinkedHashSet 底层使用 LinkedHashMap 来保存所有元素,它继承与 HashSet,其所有的方法操作上又与 HashSet 相同,因此 LinkedHashSet 的实现上非常简单,只提供了四个构造方法,并通过传递一个标识参数,调用父类的构造器,底层构造一个 LinkedHashMap 来实现,在相关操作上与父类 HashSet 的操作相同,直接调用父类 HashSet 的方法即可。LinkedHashSet 的源代码如下:

  1. public class LinkedHashSet<E>

  2.  

    extends HashSet<E>

  3.  

    implements Set<E>, Cloneable, java.io.Serializable {

  4.  

  5.  

    private static final long serialVersionUID = -2851667679971038690L;

  6.  

  7.  

    /**

  8.  

    * 构造一个带有指定初始容量和加载因子的新空链接哈希set。

  9.  

    *

  10.  

    * 底层会调用父类的构造方法,构造一个有指定初始容量和加载因子的LinkedHashMap实例。

  11.  

    * @param initialCapacity 初始容量。

  12.  

    * @param loadFactor 加载因子。

  13.  

    */

  14.  

    public LinkedHashSet(int initialCapacity, float loadFactor) {

  15.  

    super(initialCapacity, loadFactor, true);

  16.  

    }

  17.  

  18.  

    /**

  19.  

    * 构造一个带指定初始容量和默认加载因子0.75的新空链接哈希set。

  20.  

    *

  21.  

    * 底层会调用父类的构造方法,构造一个带指定初始容量和默认加载因子0.75的LinkedHashMap实例。

  22.  

    * @param initialCapacity 初始容量。

  23.  

    */

  24.  

    public LinkedHashSet(int initialCapacity) {

  25.  

    super(initialCapacity, .75f, true);

  26.  

    }

  27.  

  28.  

    /**

  29.  

    * 构造一个带默认初始容量16和加载因子0.75的新空链接哈希set。

  30.  

    *

  31.  

    * 底层会调用父类的构造方法,构造一个带默认初始容量16和加载因子0.75的LinkedHashMap实例。

  32.  

    */

  33.  

    public LinkedHashSet() {

  34.  

    super(16, .75f, true);

  35.  

    }

  36.  

  37.  

    /**

  38.  

    * 构造一个与指定collection中的元素相同的新链接哈希set。

  39.  

    *

  40.  

    * 底层会调用父类的构造方法,构造一个足以包含指定collection

  41.  

    * 中所有元素的初始容量和加载因子为0.75的LinkedHashMap实例。

  42.  

    * @param c 其中的元素将存放在此set中的collection。

  43.  

    */

  44.  

    public LinkedHashSet(Collection<? extends E> c) {

  45.  

    super(Math.max(2*c.size(), 11), .75f, true);

  46.  

    addAll(c);

  47.  

    }

  48.  

    }

以上几乎就是 LinkedHashSet 的全部代码了,那么读者可能就会怀疑了,不是说 LinkedHashSet 是基于 LinkedHashMap 实现的吗?那我为什么在源码中甚至都没有看到出现过 LinkedHashMap。不要着急,我们可以看到在 LinkedHashSet 的构造方法中,其调用了父类的构造方法。我们可以进去看一下:

  1. /**

  2.  

    * 以指定的initialCapacity和loadFactor构造一个新的空链接哈希集合。

  3.  

    * 此构造函数为包访问权限,不对外公开,实际只是是对LinkedHashSet的支持。

  4.  

    *

  5.  

    * 实际底层会以指定的参数构造一个空LinkedHashMap实例来实现。

  6.  

    * @param initialCapacity 初始容量。

  7.  

    * @param loadFactor 加载因子。

  8.  

    * @param dummy 标记。

  9.  

    */

  10.  

    HashSet(int initialCapacity, float loadFactor, boolean dummy) {

  11.  

    map = new LinkedHashMap<E,Object>(initialCapacity, loadFactor);

  12.  

    }

在父类 HashSet 中,专为 LinkedHashSet 提供的构造方法如下,该方法为包访问权限,并未对外公开。

由上述源代码可见,LinkedHashSet 通过继承 HashSet,底层使用 LinkedHashMap,以很简单明了的方式来实现了其自身的所有功能。

总结

以上就是关于 LinkedHashSet 的内容,我们只是从概述上以及构造方法这几个方面介绍了,并不是我们不想去深入其读取或者写入方法,而是其本身没有实现,只是继承于父类 HashSet 的方法。

所以我们需要注意的点是:

  • LinkedHashSet 是 Set 的一个具体实现,其维护着一个运行于所有条目的双重链接列表。此链接列表定义了迭代顺序,该迭代顺序可为插入顺序或是访问顺序。
  • LinkedHashSet 继承与 HashSet,并且其内部是通过 LinkedHashMap 来实现的。有点类似于我们之前说的LinkedHashMap 其内部是基于 Hashmap 实现一样,不过还是有一点点区别的(具体的区别大家可以自己去思考一下)。
  • 如果我们需要迭代的顺序为插入顺序或者访问顺序,那么 LinkedHashSet 是需要你首先考虑的。

ArrayList 的实现原理

ArrayList 概述

ArrayList 可以理解为动态数组,用 MSDN 中的说法,就是 Array 的复杂版本。与 Java 中的数组相比,它的容量能动态增长。ArrayList 是 List 接口的可变数组的实现。实现了所有可选列表操作,并允许包括 null 在内的所有元素。除了实现 List 接口外,此类还提供一些方法来操作内部用来存储列表的数组的大小。(此类大致上等同于 Vector 类,除了此类是不同步的。)

每个 ArrayList 实例都有一个容量,该容量是指用来存储列表元素的数组的大小。它总是至少等于列表的大小。随着向 ArrayList 中不断添加元素,其容量也自动增长。自动增长会带来数据向新数组的重新拷贝,因此,如果可预知数据量的多少,可在构造 ArrayList 时指定其容量。在添加大量元素前,应用程序也可以使用 ensureCapacity 操作来增加 ArrayList 实例的容量,这可以减少递增式再分配的数量。

注意,此实现不是同步的。如果多个线程同时访问一个 ArrayList 实例,而其中至少一个线程从结构上修改了列表,那么它必须保持外部同步。(结构上的修改是指任何添加或删除一个或多个元素的操作,或者显式调整底层数组的大小;仅仅设置元素的值不是结构上的修改。)

我们先学习了解其内部的实现原理,才能更好的理解其应用。

ArrayList 的实现

对于 ArrayList 而言,它实现 List 接口、底层使用数组保存所有元素。其操作基本上是对数组的操作。下面我们来分析 ArrayList 的源代码:

实现的接口

  1. public class ArrayList<E> extends AbstractList<E>

  2.  

    implements List<E>, RandomAccess, Cloneable, java.io.Serializable

  3.  

    {

  4.  

    }

ArrayList 继承了 AbstractList,实现了 List。它是一个数组队列,提供了相关的添加、删除、修改、遍历等功能。

ArrayList 实现了 RandmoAccess 接口,即提供了随机访问功能。RandmoAccess 是 java 中用来被 List 实现,为 List 提供快速访问功能的。在 ArrayList 中,我们即可以通过元素的序号快速获取元素对象;这就是快速随机访问。

ArrayList 实现了 Cloneable 接口,即覆盖了函数 clone(),能被克隆。 ArrayList 实现 java.io.Serializable 接口,这意味着 ArrayList 支持序列化,能通过序列化去传输。

底层使用数组实现

  1. /**

  2.  

    * The array buffer into which the elements of the ArrayList are stored.

  3.  

    * The capacity of the ArrayList is the length of this array buffer.

  4.  

    */

  5.  

    private transient Object[] elementData;

构造方法

  1.  

    /**

  2.  

    * Constructs an empty list with an initial capacity of ten.

  3.  

    */

  4.  

    public ArrayList() {

  5.  

    this(10);

  6.  

    }

  7.  

    /**

  8.  

    * Constructs an empty list with the specified initial capacity.

  9.  

    *

  10.  

    * @param initialCapacity the initial capacity of the list

  11.  

    * @throws IllegalArgumentException if the specified initial capacity

  12.  

    * is negative

  13.  

    */

  14.  

    public ArrayList(int initialCapacity) {

  15.  

    super();

  16.  

    if (initialCapacity < 0)

  17.  

    throw new IllegalArgumentException("Illegal Capacity: "+

  18.  

    initialCapacity);

  19.  

    this.elementData = new Object[initialCapacity];

  20.  

    }

  21.  

  22.  

    /**

  23.  

    * Constructs a list containing the elements of the specified

  24.  

    * collection, in the order they are returned by the collection‘s

  25.  

    * iterator.

  26.  

    *

  27.  

    * @param c the collection whose elements are to be placed into this list

  28.  

    * @throws NullPointerException if the specified collection is null

  29.  

    */

  30.  

    public ArrayList(Collection<? extends E> c) {

  31.  

    elementData = c.toArray();

  32.  

    size = elementData.length;

  33.  

    // c.toArray might (incorrectly) not return Object[] (see 6260652)

  34.  

    if (elementData.getClass() != Object[].class)

  35.  

    elementData = Arrays.copyOf(elementData, size, Object[].class);

  36.  

    }

ArrayList 提供了三种方式的构造器:

  1. public ArrayList()可以构造一个默认初始容量为10的空列表;
  2. public ArrayList(int initialCapacity)构造一个指定初始容量的空列表;
  3. public ArrayList(Collection<? extends E> c)构造一个包含指定 collection 的元素的列表,这些元素按照该collection的迭代器返回它们的顺序排列的。

存储

ArrayList 中提供了多种添加元素的方法,下面将一一进行讲解:

1.set(int index, E element):该方法首先调用rangeCheck(index)来校验 index 变量是否超出数组范围,超出则抛出异常。而后,取出原 index 位置的值,并且将新的 element 放入 Index 位置,返回 oldValue。

  1. /**

  2.  

    * Replaces the element at the specified position in this list with

  3.  

    * the specified element.

  4.  

    *

  5.  

    * @param index index of the element to replace

  6.  

    * @param element element to be stored at the specified position

  7.  

    * @return the element previously at the specified position

  8.  

    * @throws IndexOutOfBoundsException {@inheritDoc}

  9.  

    */

  10.  

    public E set(int index, E element) {

  11.  

    rangeCheck(index);

  12.  

  13.  

    E oldValue = elementData(index);

  14.  

    elementData[index] = element;

  15.  

    return oldValue;

  16.  

    }

  17.  

    /**

  18.  

    * Checks if the given index is in range. If not, throws an appropriate

  19.  

    * runtime exception. This method does *not* check if the index is

  20.  

    * negative: It is always used immediately prior to an array access,

  21.  

    * which throws an ArrayIndexOutOfBoundsException if index is negative.

  22.  

    */

  23.  

    private void rangeCheck(int index) {

  24.  

    if (index >= size)

  25.  

    throw new IndexOutOfBoundsException(outOfBoundsMsg(index));

  26.  

    }

2.add(E e):该方法是将指定的元素添加到列表的尾部。当容量不足时,会调用 grow 方法增长容量。

  1. /**

  2.  

    * Appends the specified element to the end of this list.

  3.  

    *

  4.  

    * @param e element to be appended to this list

  5.  

    * @return <tt>true</tt> (as specified by {@link Collection#add})

  6.  

    */

  7.  

    public boolean add(E e) {

  8.  

    ensureCapacityInternal(size + 1); // Increments modCount!!

  9.  

    elementData[size++] = e;

  10.  

    return true;

  11.  

    }

  12.  

    private void ensureCapacityInternal(int minCapacity) {

  13.  

    modCount++;

  14.  

    // overflow-conscious code

  15.  

    if (minCapacity - elementData.length > 0)

  16.  

    grow(minCapacity);

  17.  

    }

  18.  

    private void grow(int minCapacity) {

  19.  

    // overflow-conscious code

  20.  

    int oldCapacity = elementData.length;

  21.  

    int newCapacity = oldCapacity + (oldCapacity >> 1);

  22.  

    if (newCapacity - minCapacity < 0)

  23.  

    newCapacity = minCapacity;

  24.  

    if (newCapacity - MAX_ARRAY_SIZE > 0)

  25.  

    newCapacity = hugeCapacity(minCapacity);

  26.  

    // minCapacity is usually close to size, so this is a win:

  27.  

    elementData = Arrays.copyOf(elementData, newCapacity);

  28.  

    }

3.add(int index, E element):在 index 位置插入 element。

  1. /**

  2.  

    * Inserts the specified element at the specified position in this

  3.  

    * list. Shifts the element currently at that position (if any) and

  4.  

    * any subsequent elements to the right (adds one to their indices).

  5.  

    *

  6.  

    * @param index index at which the specified element is to be inserted

  7.  

    * @param element element to be inserted

  8.  

    * @throws IndexOutOfBoundsException {@inheritDoc}

  9.  

    */

  10.  

    public void add(int index, E element) {

  11.  

    rangeCheckForAdd(index);

  12.  

  13.  

    ensureCapacityInternal(size + 1); // Increments modCount!!

  14.  

    System.arraycopy(elementData, index, elementData, index + 1,

  15.  

    size - index);

  16.  

    elementData[index] = element;

  17.  

    size++;

  18.  

    }

4.addAll(Collection<? extends E> c) 和 addAll(int index, Collection<? extends E> c):将特定 Collection 中的元素添加到 Arraylist 末尾。

  1. /**

  2.  

    * Appends all of the elements in the specified collection to the end of

  3.  

    * this list, in the order that they are returned by the

  4.  

    * specified collection‘s Iterator. The behavior of this operation is

  5.  

    * undefined if the specified collection is modified while the operation

  6.  

    * is in progress. (This implies that the behavior of this call is

  7.  

    * undefined if the specified collection is this list, and this

  8.  

    * list is nonempty.)

  9.  

    *

  10.  

    * @param c collection containing elements to be added to this list

  11.  

    * @return <tt>true</tt> if this list changed as a result of the call

  12.  

    * @throws NullPointerException if the specified collection is null

  13.  

    */

  14.  

    public boolean addAll(Collection<? extends E> c) {

  15.  

    Object[] a = c.toArray();

  16.  

    int numNew = a.length;

  17.  

    ensureCapacityInternal(size + numNew); // Increments modCount

  18.  

    System.arraycopy(a, 0, elementData, size, numNew);

  19.  

    size += numNew;

  20.  

    return numNew != 0;

  21.  

    }

  22.  

  23.  

    /**

  24.  

    * Inserts all of the elements in the specified collection into this

  25.  

    * list, starting at the specified position. Shifts the element

  26.  

    * currently at that position (if any) and any subsequent elements to

  27.  

    * the right (increases their indices). The new elements will appear

  28.  

    * in the list in the order that they are returned by the

  29.  

    * specified collection‘s iterator.

  30.  

    *

  31.  

    * @param index index at which to insert the first element from the

  32.  

    * specified collection

  33.  

    * @param c collection containing elements to be added to this list

  34.  

    * @return <tt>true</tt> if this list changed as a result of the call

  35.  

    * @throws IndexOutOfBoundsException {@inheritDoc}

  36.  

    * @throws NullPointerException if the specified collection is null

  37.  

    */

  38.  

    public boolean addAll(int index, Collection<? extends E> c) {

  39.  

    rangeCheckForAdd(index);

  40.  

  41.  

    Object[] a = c.toArray();

  42.  

    int numNew = a.length;

  43.  

    ensureCapacityInternal(size + numNew); // Increments modCount

  44.  

  45.  

    int numMoved = size - index;

  46.  

    if (numMoved > 0)

  47.  

    System.arraycopy(elementData, index, elementData, index + numNew,

  48.  

    numMoved);

  49.  

  50.  

    System.arraycopy(a, 0, elementData, index, numNew);

  51.  

    size += numNew;

  52.  

    return numNew != 0;

  53.  

    }

在 ArrayList 的存储方法,其核心本质是在数组的某个位置将元素添加进入。但其中又会涉及到关于数组容量不够而增长等因素。

读取

这个方法就比较简单了,ArrayList 能够支持随机访问的原因也是很显然的,因为它内部的数据结构是数组,而数组本身就是支持随机访问。该方法首先会判断输入的index值是否越界,然后将数组的 index 位置的元素返回即可。

  1. /**

  2.  

    * Returns the element at the specified position in this list.

  3.  

    *

  4.  

    * @param index index of the element to return

  5.  

    * @return the element at the specified position in this list

  6.  

    * @throws IndexOutOfBoundsException {@inheritDoc}

  7.  

    */

  8.  

    public E get(int index) {

  9.  

    rangeCheck(index);

  10.  

    return (E) elementData[index];

  11.  

    }

  12.  

    private void rangeCheck(int index) {

  13.  

    if (index >= size)

  14.  

    throw new IndexOutOfBoundsException(outOfBoundsMsg(index));

  15.  

    }

删除

ArrayList 提供了根据下标或者指定对象两种方式的删除功能。需要注意的是该方法的返回值并不相同,如下:

  1. /**

  2.  

    * Removes the element at the specified position in this list.

  3.  

    * Shifts any subsequent elements to the left (subtracts one from their

  4.  

    * indices).

  5.  

    *

  6.  

    * @param index the index of the element to be removed

  7.  

    * @return the element that was removed from the list

  8.  

    * @throws IndexOutOfBoundsException {@inheritDoc}

  9.  

    */

  10.  

    public E remove(int index) {

  11.  

    rangeCheck(index);

  12.  

  13.  

    modCount++;

  14.  

    E oldValue = elementData(index);

  15.  

  16.  

    int numMoved = size - index - 1;

  17.  

    if (numMoved > 0)

  18.  

    System.arraycopy(elementData, index+1, elementData, index,

  19.  

    numMoved);

  20.  

    elementData[--size] = null; // Let gc do its work

  21.  

  22.  

    return oldValue;

  23.  

    }

  24.  

    /**

  25.  

    * Removes the first occurrence of the specified element from this list,

  26.  

    * if it is present. If the list does not contain the element, it is

  27.  

    * unchanged. More formally, removes the element with the lowest index

  28.  

    * <tt>i</tt> such that

  29.  

    * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>

  30.  

    * (if such an element exists). Returns <tt>true</tt> if this list

  31.  

    * contained the specified element (or equivalently, if this list

  32.  

    * changed as a result of the call).

  33.  

    *

  34.  

    * @param o element to be removed from this list, if present

  35.  

    * @return <tt>true</tt> if this list contained the specified element

  36.  

    */

  37.  

    public boolean remove(Object o) {

  38.  

    if (o == null) {

  39.  

    for (int index = 0; index < size; index++)

  40.  

    if (elementData[index] == null) {

  41.  

    fastRemove(index);

  42.  

    return true;

  43.  

    }

  44.  

    } else {

  45.  

    for (int index = 0; index < size; index++)

  46.  

    if (o.equals(elementData[index])) {

  47.  

    fastRemove(index);

  48.  

    return true;

  49.  

    }

  50.  

    }

  51.  

    return false;

  52.  

    }

注意:从数组中移除元素的操作,也会导致被移除的元素以后的所有元素的向左移动一个位置。

调整数组容量

从上面介绍的向 ArrayList 中存储元素的代码中,我们看到,每当向数组中添加元素时,都要去检查添加后元素的个数是否会超出当前数组的长度,如果超出,数组将会进行扩容,以满足添加数据的需求。数组扩容有两个方法,其中开发者可以通过一个 public 的方法ensureCapacity(int minCapacity)来增加 ArrayList 的容量,而在存储元素等操作过程中,如果遇到容量不足,会调用priavte方法private void ensureCapacityInternal(int minCapacity)实现。

  1. public void ensureCapacity(int minCapacity) {

  2.  

    if (minCapacity > 0)

  3.  

    ensureCapacityInternal(minCapacity);

  4.  

    }

  5.  

  6.  

    private void ensureCapacityInternal(int minCapacity) {

  7.  

    modCount++;

  8.  

    // overflow-conscious code

  9.  

    if (minCapacity - elementData.length > 0)

  10.  

    grow(minCapacity);

  11.  

    }

  12.  

    /**

  13.  

    * Increases the capacity to ensure that it can hold at least the

  14.  

    * number of elements specified by the minimum capacity argument.

  15.  

    *

  16.  

    * @param minCapacity the desired minimum capacity

  17.  

    */

  18.  

    private void grow(int minCapacity) {

  19.  

    // overflow-conscious code

  20.  

    int oldCapacity = elementData.length;

  21.  

    int newCapacity = oldCapacity + (oldCapacity >> 1);

  22.  

    if (newCapacity - minCapacity < 0)

  23.  

    newCapacity = minCapacity;

  24.  

    if (newCapacity - MAX_ARRAY_SIZE > 0)

  25.  

    newCapacity = hugeCapacity(minCapacity);

  26.  

    // minCapacity is usually close to size, so this is a win:

  27.  

    elementData = Arrays.copyOf(elementData, newCapacity);

  28.  

    }

从上述代码中可以看出,数组进行扩容时,会将老数组中的元素重新拷贝一份到新的数组中,每次数组容量的增长大约是其原容量的 1.5 倍(从int newCapacity = oldCapacity + (oldCapacity >> 1)这行代码得出)。这种操作的代价是很高的,因此在实际使用时,我们应该尽量避免数组容量的扩张。当我们可预知要保存的元素的多少时,要在构造 ArrayList 实例时,就指定其容量,以避免数组扩容的发生。或者根据实际需求,通过调用ensureCapacity 方法来手动增加 ArrayList 实例的容量。

Fail-Fast 机制

ArrayList 也采用了快速失败的机制,通过记录 modCount 参数来实现。在面对并发的修改时,迭代器很快就会完全失败,而不是冒着在将来某个不确定时间发生任意不确定行为的风险。 关于 Fail-Fast 的更详细的介绍,我在之前将 HashMap 中已经提到。

LinkedList 的实现原理

概述

LinkedList 和 ArrayList 一样,都实现了 List 接口,但其内部的数据结构有本质的不同。LinkedList 是基于链表实现的(通过名字也能区分开来),所以它的插入和删除操作比 ArrayList 更加高效。但也是由于其为基于链表的,所以随机访问的效率要比 ArrayList 差。

看一下 LinkedList 的类的定义:

  1. public class LinkedList<E>

  2.  

    extends AbstractSequentialList<E>

  3.  

    implements List<E>, Deque<E>, Cloneable, java.io.Serializable

  4.  

    {}

LinkedList 继承自 AbstractSequenceList,实现了 List、Deque、Cloneable、java.io.Serializable 接口。AbstractSequenceList 提供了List接口骨干性的实现以减少实现 List 接口的复杂度,Deque 接口定义了双端队列的操作。

在 LinkedList 中除了本身自己的方法外,还提供了一些可以使其作为栈、队列或者双端队列的方法。这些方法可能彼此之间只是名字不同,以使得这些名字在特定的环境中显得更加合适。

LinkedList 也是 fail-fast 的(前边提过很多次了)。

LinkedList 源码解读

数据结构

LinkedList 是基于链表结构实现,所以在类中包含了 first 和 last 两个指针(Node)。Node 中包含了上一个节点和下一个节点的引用,这样就构成了双向的链表。每个 Node 只能知道自己的前一个节点和后一个节点,但对于链表来说,这已经足够了。

  1. transient int size = 0;

  2.  

    transient Node<E> first; //链表的头指针

  3.  

    transient Node<E> last; //尾指针

  4.  

    //存储对象的结构 Node, LinkedList的内部类

  5.  

    private static class Node<E> {

  6.  

    E item;

  7.  

    Node<E> next; // 指向下一个节点

  8.  

    Node<E> prev; //指向上一个节点

  9.  

  10.  

    Node(Node<E> prev, E element, Node<E> next) {

  11.  

    this.item = element;

  12.  

    this.next = next;

  13.  

    this.prev = prev;

  14.  

    }

  15.  

    }

存储

add(E e)

该方法是在链表的 end 添加元素,其调用了自己的方法 linkLast(E e)。

该方法首先将 last 的 Node 引用指向了一个新的 Node(l),然后根据l新建了一个 newNode,其中的元素就为要添加的 e;而后,我们让 last 指向了 newNode。接下来是自身进行维护该链表。

  1. /**

  2.  

    * Appends the specified element to the end of this list.

  3.  

    *

  4.  

    * <p>This method is equivalent to {@link #addLast}.

  5.  

    *

  6.  

    * @param e element to be appended to this list

  7.  

    * @return {@code true} (as specified by {@link Collection#add})

  8.  

    */

  9.  

    public boolean add(E e) {

  10.  

    linkLast(e);

  11.  

    return true;

  12.  

    }

  13.  

    /**

  14.  

    * Links e as last element.

  15.  

    */

  16.  

    void linkLast(E e) {

  17.  

    final Node<E> l = last;

  18.  

    final Node<E> newNode = new Node<>(l, e, null);

  19.  

    last = newNode;

  20.  

    if (l == null)

  21.  

    first = newNode;

  22.  

    else

  23.  

    l.next = newNode;

  24.  

    size++;

  25.  

    modCount++;

  26.  

    }

add(int index, E element)

该方法是在指定 index 位置插入元素。如果 index 位置正好等于 size,则调用 linkLast(element) 将其插入末尾;否则调用 linkBefore(element, node(index))方法进行插入。该方法的实现在下面,大家可以自己仔细的分析一下。(分析链表的时候最好能够边画图边分析)

  1. /**

  2.  

    * Inserts the specified element at the specified position in this list.

  3.  

    * Shifts the element currently at that position (if any) and any

  4.  

    * subsequent elements to the right (adds one to their indices).

  5.  

    *

  6.  

    * @param index index at which the specified element is to be inserted

  7.  

    * @param element element to be inserted

  8.  

    * @throws IndexOutOfBoundsException {@inheritDoc}

  9.  

    */

  10.  

    public void add(int index, E element) {

  11.  

    checkPositionIndex(index);

  12.  

  13.  

    if (index == size)

  14.  

    linkLast(element);

  15.  

    else

  16.  

    linkBefore(element, node(index));

  17.  

    }

  18.  

    /**

  19.  

    * Inserts element e before non-null Node succ.

  20.  

    */

  21.  

    void linkBefore(E e, Node<E> succ) {

  22.  

    // assert succ != null;

  23.  

    final Node<E> pred = succ.prev;

  24.  

    final Node<E> newNode = new Node<>(pred, e, succ);

  25.  

    succ.prev = newNode;

  26.  

    if (pred == null)

  27.  

    first = newNode;

  28.  

    else

  29.  

    pred.next = newNode;

  30.  

    size++;

  31.  

    modCount++;

  32.  

    }

LinkedList 的方法实在是太多,在这没法一一举例分析。但很多方法其实都只是在调用别的方法而已,所以建议大家将其几个最核心的添加的方法搞懂就可以了,比如 linkBefore、linkLast。其本质也就是链表之间的删除添加等。

ConcurrentHashMap 的实现原理

概述

我们在之前的博文中了解到关于 HashMap 和 Hashtable 这两种集合。其中 HashMap 是非线程安全的,当我们只有一个线程在使用 HashMap 的时候,自然不会有问题,但如果涉及到多个线程,并且有读有写的过程中,HashMap 就不能满足我们的需要了(fail-fast)。在不考虑性能问题的时候,我们的解决方案有 Hashtable 或者Collections.synchronizedMap(hashMap),这两种方式基本都是对整个 hash 表结构做锁定操作的,这样在锁表的期间,别的线程就需要等待了,无疑性能不高。

所以我们在本文中学习一个 util.concurrent 包的重要成员,ConcurrentHashMap。

ConcurrentHashMap 的实现是依赖于 Java 内存模型,所以我们在了解 ConcurrentHashMap 的前提是必须了解Java 内存模型。但 Java 内存模型并不是本文的重点,所以我假设读者已经对 Java 内存模型有所了解。

ConcurrentHashMap 分析

ConcurrentHashMap 的结构是比较复杂的,都深究去本质,其实也就是数组和链表而已。我们由浅入深慢慢的分析其结构。

先简单分析一下,ConcurrentHashMap 的成员变量中,包含了一个 Segment 的数组(final Segment<K,V>[] segments;),而 Segment 是 ConcurrentHashMap 的内部类,然后在 Segment 这个类中,包含了一个 HashEntry 的数组(transient volatile HashEntry<K,V>[] table;)。而 HashEntry 也是 ConcurrentHashMap 的内部类。HashEntry 中,包含了 key 和 value 以及 next 指针(类似于 HashMap 中 Entry),所以 HashEntry 可以构成一个链表。

所以通俗的讲,ConcurrentHashMap 数据结构为一个 Segment 数组,Segment 的数据结构为 HashEntry 的数组,而 HashEntry 存的是我们的键值对,可以构成链表。

首先,我们看一下 HashEntry 类。

HashEntry

HashEntry 用来封装散列映射表中的键值对。在 HashEntry 类中,key,hash 和 next 域都被声明为 final 型,value 域被声明为 volatile 型。其类的定义为:

  1. static final class HashEntry<K,V> {

  2.  

    final int hash;

  3.  

    final K key;

  4.  

    volatile V value;

  5.  

    volatile HashEntry<K,V> next;

  6.  

  7.  

    HashEntry(int hash, K key, V value, HashEntry<K,V> next) {

  8.  

    this.hash = hash;

  9.  

    this.key = key;

  10.  

    this.value = value;

  11.  

    this.next = next;

  12.  

    }

  13.  

    ...

  14.  

    ...

  15.  

    }

HashEntry 的学习可以类比着 HashMap 中的 Entry。我们的存储键值对的过程中,散列的时候如果发生“碰撞”,将采用“分离链表法”来处理碰撞:把碰撞的 HashEntry 对象链接成一个链表。

如下图,我们在一个空桶中插入 A、B、C 两个 HashEntry 对象后的结构图(其实应该为键值对,在这进行了简化以方便更容易理解):

Segment

Segment 的类定义为static final class Segment<K,V> extends ReentrantLock implements Serializable。其继承于 ReentrantLock 类,从而使得 Segment 对象可以充当锁的角色。Segment 中包含HashEntry 的数组,其可以守护其包含的若干个桶(HashEntry的数组)。Segment 在某些意义上有点类似于 HashMap了,都是包含了一个数组,而数组中的元素可以是一个链表。

table:table 是由 HashEntry 对象组成的数组如果散列时发生碰撞,碰撞的 HashEntry 对象就以链表的形式链接成一个链表table数组的数组成员代表散列映射表的一个桶每个 table 守护整个 ConcurrentHashMap 包含桶总数的一部分如果并发级别为 16,table 则守护 ConcurrentHashMap 包含的桶总数的 1/16。

count 变量是计算器,表示每个 Segment 对象管理的 table 数组(若干个 HashEntry 的链表)包含的HashEntry 对象的个数。之所以在每个Segment对象中包含一个 count 计数器,而不在 ConcurrentHashMap 中使用全局的计数器,是为了避免出现“热点域”而影响并发性。

  1. /**

  2.  

    * Segments are specialized versions of hash tables. This

  3.  

    * subclasses from ReentrantLock opportunistically, just to

  4.  

    * simplify some locking and avoid separate construction.

  5.  

    */

  6.  

    static final class Segment<K,V> extends ReentrantLock implements Serializable {

  7.  

    /**

  8.  

    * The per-segment table. Elements are accessed via

  9.  

    * entryAt/setEntryAt providing volatile semantics.

  10.  

    */

  11.  

    transient volatile HashEntry<K,V>[] table;

  12.  

  13.  

    /**

  14.  

    * The number of elements. Accessed only either within locks

  15.  

    * or among other volatile reads that maintain visibility.

  16.  

    */

  17.  

    transient int count;

  18.  

    transient int modCount;

  19.  

    /**

  20.  

    * 装载因子

  21.  

    */

  22.  

    final float loadFactor;

  23.  

    }

我们通过下图来展示一下插入 ABC 三个节点后,Segment 的示意图:

其实从我个人角度来说,Segment结构是与HashMap很像的。

ConcurrentHashMap

ConcurrentHashMap 的结构中包含的 Segment 的数组,在默认的并发级别会创建包含 16 个 Segment 对象的数组。通过我们上面的知识,我们知道每个 Segment 又包含若干个散列表的桶,每个桶是由 HashEntry 链接起来的一个链表。如果 key 能够均匀散列,每个 Segment 大约守护整个散列表桶总数的 1/16。

下面我们还有通过一个图来演示一下 ConcurrentHashMap 的结构:

并发写操作

在 ConcurrentHashMap 中,当执行 put 方法的时候,会需要加锁来完成。我们通过代码来解释一下具体过程: 当我们 new 一个 ConcurrentHashMap 对象,并且执行put操作的时候,首先会执行 ConcurrentHashMap 类中的 put 方法,该方法源码为:

  1. /**

  2.  

    * Maps the specified key to the specified value in this table.

  3.  

    * Neither the key nor the value can be null.

  4.  

    *

  5.  

    * <p> The value can be retrieved by calling the <tt>get</tt> method

  6.  

    * with a key that is equal to the original key.

  7.  

    *

  8.  

    * @param key key with which the specified value is to be associated

  9.  

    * @param value value to be associated with the specified key

  10.  

    * @return the previous value associated with <tt>key</tt>, or

  11.  

    * <tt>null</tt> if there was no mapping for <tt>key</tt>

  12.  

    * @throws NullPointerException if the specified key or value is null

  13.  

    */

  14.  

    @SuppressWarnings("unchecked")

  15.  

    public V put(K key, V value) {

  16.  

    Segment<K,V> s;

  17.  

    if (value == null)

  18.  

    throw new NullPointerException();

  19.  

    int hash = hash(key);

  20.  

    int j = (hash >>> segmentShift) & segmentMask;

  21.  

    if ((s = (Segment<K,V>)UNSAFE.getObject // nonvolatile; recheck

  22.  

    (segments, (j << SSHIFT) + SBASE)) == null) // in ensureSegment

  23.  

    s = ensureSegment(j);

  24.  

    return s.put(key, hash, value, false);

  25.  

    }

我们通过注释可以了解到,ConcurrentHashMap 不允许空值。该方法首先有一个 Segment 的引用 s,然后会通过 hash() 方法对 key 进行计算,得到哈希值;继而通过调用 Segment 的 put(K key, int hash, V value, boolean onlyIfAbsent)方法进行存储操作。该方法源码为:

  1. final V put(K key, int hash, V value, boolean onlyIfAbsent) {

  2.  

    //加锁,这里是锁定的Segment而不是整个ConcurrentHashMap

  3.  

    HashEntry<K,V> node = tryLock() ? null :scanAndLockForPut(key, hash, value);

  4.  

    V oldValue;

  5.  

    try {

  6.  

    HashEntry<K,V>[] tab = table;

  7.  

    //得到hash对应的table中的索引index

  8.  

    int index = (tab.length - 1) & hash;

  9.  

    //找到hash对应的是具体的哪个桶,也就是哪个HashEntry链表

  10.  

    HashEntry<K,V> first = entryAt(tab, index);

  11.  

    for (HashEntry<K,V> e = first;;) {

  12.  

    if (e != null) {

  13.  

    K k;

  14.  

    if ((k = e.key) == key ||

  15.  

    (e.hash == hash && key.equals(k))) {

  16.  

    oldValue = e.value;

  17.  

    if (!onlyIfAbsent) {

  18.  

    e.value = value;

  19.  

    ++modCount;

  20.  

    }

  21.  

    break;

  22.  

    }

  23.  

    e = e.next;

  24.  

    }

  25.  

    else {

  26.  

    if (node != null)

  27.  

    node.setNext(first);

  28.  

    else

  29.  

    node = new HashEntry<K,V>(hash, key, value, first);

  30.  

    int c = count + 1;

  31.  

    if (c > threshold && tab.length < MAXIMUM_CAPACITY)

  32.  

    rehash(node);

  33.  

    else

  34.  

    setEntryAt(tab, index, node);

  35.  

    ++modCount;

  36.  

    count = c;

  37.  

    oldValue = null;

  38.  

    break;

  39.  

    }

  40.  

    }

  41.  

    } finally {

  42.  

    //解锁

  43.  

    unlock();

  44.  

    }

  45.  

    return oldValue;

  46.  

    }

关于该方法的某些关键步骤,在源码上加上了注释。

需要注意的是:加锁操作是针对的 hash 值对应的某个 Segment,而不是整个 ConcurrentHashMap。因为 put 操作只是在这个 Segment 中完成,所以并不需要对整个 ConcurrentHashMap 加锁。所以,此时,其他的线程也可以对另外的 Segment 进行 put 操作,因为虽然该 Segment 被锁住了,但其他的 Segment 并没有加锁。同时,读线程并不会因为本线程的加锁而阻塞。

正是因为其内部的结构以及机制,所以 ConcurrentHashMap 在并发访问的性能上要比Hashtable和同步包装之后的HashMap的性能提高很多。在理想状态下,ConcurrentHashMap 可以支持 16 个线程执行并发写操作(如果并发级别设置为 16),及任意数量线程的读操作。

总结

在实际的应用中,散列表一般的应用场景是:除了少数插入操作和删除操作外,绝大多数都是读取操作,而且读操作在大多数时候都是成功的。正是基于这个前提,ConcurrentHashMap 针对读操作做了大量的优化。通过 HashEntry 对象的不变性和用 volatile 型变量协调线程间的内存可见性,使得 大多数时候,读操作不需要加锁就可以正确获得值。这个特性使得 ConcurrentHashMap 的并发性能在分离锁的基础上又有了近一步的提高。

ConcurrentHashMap 是一个并发散列映射表的实现,它允许完全并发的读取,并且支持给定数量的并发更新。相比于 HashTable 和用同步包装器包装的 HashMap(Collections.synchronizedMap(new HashMap())),ConcurrentHashMap 拥有更高的并发性。在 HashTable 和由同步包装器包装的 HashMap 中,使用一个全局的锁来同步不同线程间的并发访问。同一时间点,只能有一个线程持有锁,也就是说在同一时间点,只能有一个线程能访问容器。这虽然保证多线程间的安全并发访问,但同时也导致对容器的访问变成串行化的了。

ConcurrentHashMap 的高并发性主要来自于三个方面:

  • 用分离锁实现多个线程间的更深层次的共享访问。
  • 用 HashEntery 对象的不变性来降低执行读操作的线程在遍历链表期间对加锁的需求。
  • 通过对同一个 Volatile 变量的写 / 读访问,协调不同线程间读 / 写操作的内存可见性。

使用分离锁,减小了请求 同一个锁的频率。

通过 HashEntery 对象的不变性及对同一个 Volatile 变量的读 / 写来协调内存可见性,使得 读操作大多数时候不需要加锁就能成功获取到需要的值。由于散列映射表在实际应用中大多数操作都是成功的 读操作,所以 2 和 3 既可以减少请求同一个锁的频率,也可以有效减少持有锁的时间。通过减小请求同一个锁的频率和尽量减少持有锁的时间 ,使得 ConcurrentHashMap 的并发性相对于 HashTable 和用同步包装器包装的 HashMap有了质的提高。

LinkedHashMap 与 LRUcache

LRU 缓存介绍

我们平时总会有一个电话本记录所有朋友的电话,但是,如果有朋友经常联系,那些朋友的电话号码不用翻电话本我们也能记住,但是,如果长时间没有联系了,要再次联系那位朋友的时候,我们又不得不求助电话本,但是,通过电话本查找还是很费时间的。但是,我们大脑能够记住的东西是一定的,我们只能记住自己最熟悉的,而长时间不熟悉的自然就忘记了。

其实,计算机也用到了同样的一个概念,我们用缓存来存放以前读取的数据,而不是直接丢掉,这样,再次读取的时候,可以直接在缓存里面取,而不用再重新查找一遍,这样系统的反应能力会有很大提高。但是,当我们读取的个数特别大的时候,我们不可能把所有已经读取的数据都放在缓存里,毕竟内存大小是一定的,我们一般把最近常读取的放在缓存里(相当于我们把最近联系的朋友的姓名和电话放在大脑里一样)。

LRU 缓存利用了这样的一种思想。LRU 是 Least Recently Used 的缩写,翻译过来就是“最近最少使用”,也就是说,LRU 缓存把最近最少使用的数据移除,让给最新读取的数据。而往往最常读取的,也是读取次数最多的,所以,利用 LRU 缓存,我们能够提高系统的 performance。

实现

要实现 LRU 缓存,我们首先要用到一个类 LinkedHashMap。

用这个类有两大好处:一是它本身已经实现了按照访问顺序的存储,也就是说,最近读取的会放在最前面,最最不常读取的会放在最后(当然,它也可以实现按照插入顺序存储)。第二,LinkedHashMap 本身有一个方法用于判断是否需要移除最不常读取的数,但是,原始方法默认不需要移除(这是,LinkedHashMap 相当于一个linkedlist),所以,我们需要 override 这样一个方法,使得当缓存里存放的数据个数超过规定个数后,就把最不常用的移除掉。关于 LinkedHashMap 中已经有详细的介绍。

代码如下:(可直接复制,也可以通过LRUcache-Java下载)

  1. import java.util.LinkedHashMap;

  2.  

    import java.util.Collection;

  3.  

    import java.util.Map;

  4.  

    import java.util.ArrayList;

  5.  

  6.  

    /**

  7.  

    * An LRU cache, based on <code>LinkedHashMap</code>.

  8.  

    *

  9.  

    * <p>

  10.  

    * This cache has a fixed maximum number of elements (<code>cacheSize</code>).

  11.  

    * If the cache is full and another entry is added, the LRU (least recently

  12.  

    * used) entry is dropped.

  13.  

    *

  14.  

    * <p>

  15.  

    * This class is thread-safe. All methods of this class are synchronized.

  16.  

    *

  17.  

    * <p>

  18.  

    * Author: Christian d‘Heureuse, Inventec Informatik AG, Zurich, Switzerland<br>

  19.  

    * Multi-licensed: EPL / LGPL / GPL / AL / BSD.

  20.  

    */

  21.  

    public class LRUCache<K, V> {

  22.  

    private static final float hashTableLoadFactor = 0.75f;

  23.  

    private LinkedHashMap<K, V> map;

  24.  

    private int cacheSize;

  25.  

  26.  

    /**

  27.  

    * Creates a new LRU cache. 在该方法中,new LinkedHashMap<K,V>(hashTableCapacity,

  28.  

    * hashTableLoadFactor, true)中,true代表使用访问顺序

  29.  

    *

  30.  

    * @param cacheSize

  31.  

    * the maximum number of entries that will be kept in this cache.

  32.  

    */

  33.  

    public LRUCache(int cacheSize) {

  34.  

    this.cacheSize = cacheSize;

  35.  

    int hashTableCapacity = (int) Math

  36.  

    .ceil(cacheSize / hashTableLoadFactor) + 1;

  37.  

    map = new LinkedHashMap<K, V>(hashTableCapacity, hashTableLoadFactor,

  38.  

    true) {

  39.  

    // (an anonymous inner class)

  40.  

    private static final long serialVersionUID = 1;

  41.  

  42.  

    @Override

  43.  

    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {

  44.  

    return size() > LRUCache.this.cacheSize;

  45.  

    }

  46.  

    };

  47.  

    }

  48.  

  49.  

    /**

  50.  

    * Retrieves an entry from the cache.<br>

  51.  

    * The retrieved entry becomes the MRU (most recently used) entry.

  52.  

    *

  53.  

    * @param key

  54.  

    * the key whose associated value is to be returned.

  55.  

    * @return the value associated to this key, or null if no value with this

  56.  

    * key exists in the cache.

  57.  

    */

  58.  

    public synchronized V get(K key) {

  59.  

    return map.get(key);

  60.  

    }

  61.  

  62.  

    /**

  63.  

    * Adds an entry to this cache. The new entry becomes the MRU (most recently

  64.  

    * used) entry. If an entry with the specified key already exists in the

  65.  

    * cache, it is replaced by the new entry. If the cache is full, the LRU

  66.  

    * (least recently used) entry is removed from the cache.

  67.  

    *

  68.  

    * @param key

  69.  

    * the key with which the specified value is to be associated.

  70.  

    * @param value

  71.  

    * a value to be associated with the specified key.

  72.  

    */

  73.  

    public synchronized void put(K key, V value) {

  74.  

    map.put(key, value);

  75.  

    }

  76.  

  77.  

    /**

  78.  

    * Clears the cache.

  79.  

    */

  80.  

    public synchronized void clear() {

  81.  

    map.clear();

  82.  

    }

  83.  

  84.  

    /**

  85.  

    * Returns the number of used entries in the cache.

  86.  

    *

  87.  

    * @return the number of entries currently in the cache.

  88.  

    */

  89.  

    public synchronized int usedEntries() {

  90.  

    return map.size();

  91.  

    }

  92.  

  93.  

    /**

  94.  

    * Returns a <code>Collection</code> that contains a copy of all cache

  95.  

    * entries.

  96.  

    *

  97.  

    * @return a <code>Collection</code> with a copy of the cache content.

  98.  

    */

  99.  

    public synchronized Collection<Map.Entry<K, V>> getAll() {

  100.  

    return new ArrayList<Map.Entry<K, V>>(map.entrySet());

  101.  

    }

  102.  

  103.  

    // Test routine for the LRUCache class.

  104.  

    public static void main(String[] args) {

  105.  

    LRUCache<String, String> c = new LRUCache<String, String>(3);

  106.  

    c.put("1", "one"); // 1

  107.  

    c.put("2", "two"); // 2 1

  108.  

    c.put("3", "three"); // 3 2 1

  109.  

    c.put("4", "four"); // 4 3 2

  110.  

    if (c.get("2") == null)

  111.  

    throw new Error(); // 2 4 3

  112.  

    c.put("5", "five"); // 5 2 4

  113.  

    c.put("4", "second four"); // 4 5 2

  114.  

    // Verify cache content.

  115.  

    if (c.usedEntries() != 3)

  116.  

    throw new Error();

  117.  

    if (!c.get("4").equals("second four"))

  118.  

    throw new Error();

  119.  

    if (!c.get("5").equals("five"))

  120.  

    throw new Error();

  121.  

    if (!c.get("2").equals("two"))

  122.  

    throw new Error();

  123.  

    // List cache content.

  124.  

    for (Map.Entry<String, String> e : c.getAll())

  125.  

    System.out.println(e.getKey() + " : " + e.getValue());

  126.  

    }

  127.  

    }


HashSet 和 HashMap 的比较

HashMap 和 HashSet 都是 collection 框架的一部分,它们让我们能够使用对象的集合。collection 框架有自己的接口和实现,主要分为 Set 接口,List 接口和 Queue 接口。它们有各自的特点,Set 的集合里不允许对象有重复的值,List 允许有重复,它对集合中的对象进行索引,Queue 的工作原理是 FCFS 算法(First Come, First Serve)。

首先让我们来看看什么是 HashMap 和 HashSet,然后再来比较它们之间的分别。

什么是 HashSet

HashSet 实现了 Set 接口,它不允许集合中有重复的值,当我们提到 HashSet 时,第一件事情就是在将对象存储在 HashSet 之前,要先确保对象重写 equals()和 hashCode()方法,这样才能比较对象的值是否相等,以确保set中没有储存相等的对象。如果我们没有重写这两个方法,将会使用这个方法的默认实现。

public boolean add(Obje

HashMap 的实现原理

HashMap 概述

HashMap 是基于哈希表的 Map 接口的非同步实现。此实现提供所有可选的映射操作,并允许使用 null 值和 null 键。此类不保证映射的顺序,特别是它不保证该顺序恒久不变。

此实现假定哈希函数将元素适当地分布在各桶之间,可为基本操作(get 和 put)提供稳定的性能。迭代 collection 视图所需的时间与 HashMap 实例的“容量”(桶的数量)及其大小(键-值映射关系数)成比例。所以,如果迭代性能很重要,则不要将初始容量设置得太高或将加载因子设置得太低。也许大家开始对这段话有一点不太懂,不过不用担心,当你读完这篇文章后,就能深切理解这其中的含义了。

需要注意的是:Hashmap 不是同步的,如果多个线程同时访问一个 HashMap,而其中至少一个线程从结构上(指添加或者删除一个或多个映射关系的任何操作)修改了,则必须保持外部同步,以防止对映射进行意外的非同步访问。

HashMap 的数据结构

在 Java 编程语言中,最基本的结构就是两种,一个是数组,另外一个是指针(引用),HashMap 就是通过这两个数据结构进行实现。HashMap实际上是一个“链表散列”的数据结构,即数组和链表的结合体。

从上图中可以看出,HashMap 底层就是一个数组结构,数组中的每一项又是一个链表。当新建一个 HashMap 的时候,就会初始化一个数组。

我们通过 JDK 中的 HashMap 源码进行一些学习,首先看一下构造函数:

  1. public HashMap(int initialCapacity, float loadFactor) {

  2.  

    if (initialCapacity < 0)

  3.  

    throw new IllegalArgumentException("Illegal initial capacity: " +

  4.  

    initialCapacity);

  5.  

    if (initialCapacity > MAXIMUM_CAPACITY)

  6.  

    initialCapacity = MAXIMUM_CAPACITY;

  7.  

    if (loadFactor <= 0 || Float.isNaN(loadFactor))

  8.  

    throw new IllegalArgumentException("Illegal load factor: " +

  9.  

    loadFactor);

  10.  

  11.  

    // Find a power of 2 >= initialCapacity

  12.  

    int capacity = 1;

  13.  

    while (capacity < initialCapacity)

  14.  

    capacity <<= 1;

  15.  

  16.  

    this.loadFactor = loadFactor;

  17.  

    threshold = (int)Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);

  18.  

    table = new Entry[capacity];

  19.  

    useAltHashing = sun.misc.VM.isBooted() &&

  20.  

    (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);

  21.  

    init();

  22.  

    }

我们着重看一下第 18 行代码table = new Entry[capacity];。这不就是 Java 中数组的创建方式吗?也就是说在构造函数中,其创建了一个 Entry 的数组,其大小为 capacity(目前我们还不需要太了解该变量含义),那么 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.  

    final int hash;

  6.  

    ……

  7.  

    }

我们目前还是只着重核心的部分,Entry 是一个 static class,其中包含了 key 和 value,也就是键值对,另外还包含了一个 next 的 Entry 指针。我们可以总结出:Entry 就是数组中的元素,每个 Entry 其实就是一个 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.  

    //其允许存放null的key和null的value,当其key为null时,调用putForNullKey方法,放入到table[0]的这个位置

  15.  

    if (key == null)

  16.  

    return putForNullKey(value);

  17.  

    //通过调用hash方法对key进行哈希,得到哈希之后的数值。该方法实现可以通过看源码,其目的是为了尽可能的让键值对可以分不到不同的桶中

  18.  

    int hash = hash(key);

  19.  

    //根据上一步骤中求出的hash得到在数组中是索引i

  20.  

    int i = indexFor(hash, table.length);

  21.  

    //如果i处的Entry不为null,则通过其next指针不断遍历e元素的下一个元素。

  22.  

    for (Entry<K,V> e = table[i]; e != null; e = e.next) {

  23.  

    Object k;

  24.  

    if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {

  25.  

    V oldValue = e.value;

  26.  

    e.value = value;

  27.  

    e.recordAccess(this);

  28.  

    return oldValue;

  29.  

    }

  30.  

    }

  31.  

  32.  

    modCount++;

  33.  

    addEntry(hash, key, value, i);

  34.  

    return null;

  35.  

    }

我们看一下方法的标准注释:在注释中首先提到了,当我们 put 的时候,如果 key 存在了,那么新的 value 会代替旧的 value,并且如果 key 存在的情况下,该方法返回的是旧的 value,如果 key 不存在,那么返回 null。

从上面的源代码中可以看出:当我们往 HashMap 中 put 元素的时候,先根据 key 的 hashCode 重新计算 hash 值,根据 hash 值得到这个元素在数组中的位置(即下标),如果数组该位置上已经存放有其他元素了,那么在这个位置上的元素将以链表的形式存放,新加入的放在链头,最先加入的放在链尾。如果数组该位置上没有元素,就直接将该元素放到此数组中的该位置上。

addEntry(hash, key, value, i)方法根据计算出的 hash 值,将 key-value 对放在数组 table 的 i 索引处。addEntry 是 HashMap 提供的一个包访问权限的方法,代码如下:

  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.  

    }

  17.  

    void createEntry(int hash, K key, V value, int bucketIndex) {

  18.  

    // 获取指定 bucketIndex 索引处的 Entry

  19.  

    Entry<K,V> e = table[bucketIndex];

  20.  

    // 将新创建的 Entry 放入 bucketIndex 索引处,并让新的 Entry 指向原来的 Entr

  21.  

    table[bucketIndex] = new Entry<>(hash, key, value, e);

  22.  

    size++;

  23.  

    }

当系统决定存储 HashMap 中的 key-value 对时,完全没有考虑 Entry 中的 value,仅仅只是根据 key 来计算并决定每个 Entry 的存储位置。我们完全可以把 Map 集合中的 value 当成 key 的附属,当系统决定了 key 的存储位置之后,value 随之保存在那里即可。

hash(int h)方法根据 key 的 hashCode 重新计算一次散列。此算法加入了高位计算,防止低位不变,高位变化时,造成的 hash 冲突。

  1. final int hash(Object k) {

  2.  

    int h = 0;

  3.  

    if (useAltHashing) {

  4.  

    if (k instanceof String) {

  5.  

    return sun.misc.Hashing.stringHash32((String) k);

  6.  

    }

  7.  

    h = hashSeed;

  8.  

    }

  9.  

    //得到k的hashcode值

  10.  

    h ^= k.hashCode();

  11.  

    //进行计算

  12.  

    h ^= (h >>> 20) ^ (h >>> 12);

  13.  

    return h ^ (h >>> 7) ^ (h >>> 4);

  14.  

    }

我们可以看到在 HashMap 中要找到某个元素,需要根据 key 的 hash 值来求得对应数组中的位置。如何计算这个位置就是 hash 算法。前面说过 HashMap 的数据结构是数组和链表的结合,所以我们当然希望这个 HashMap 里面的 元素位置尽量的分布均匀些,尽量使得每个位置上的元素数量只有一个,那么当我们用 hash 算法求得这个位置的时候,马上就可以知道对应位置的元素就是我们要的,而不用再去遍历链表,这样就大大优化了查询的效率。

对于任意给定的对象,只要它的 hashCode() 返回值相同,那么程序调用 hash(int h) 方法所计算得到的 hash 码值总是相同的。我们首先想到的就是把 hash 值对数组长度取模运算,这样一来,元素的分布相对来说是比较均匀的。但是,“模”运算的消耗还是比较大的,在 HashMap 中是这样做的:调用 indexFor(int h, int length) 方法来计算该对象应该保存在 table 数组的哪个索引处。indexFor(int h, int length) 方法的代码如下:

  1. /**

  2.  

    * Returns index for hash code h.

  3.  

    */

  4.  

    static int indexFor(int h, int length) {

  5.  

    return h & (length-1);

  6.  

    }

这个方法非常巧妙,它通过 h & (table.length -1) 来得到该对象的保存位,而 HashMap 底层数组的长度总是 2 的 n 次方,这是 HashMap 在速度上的优化。在 HashMap 构造器中有如下代码:

  1. // Find a power of 2 >= initialCapacity

  2.  

    int capacity = 1;

  3.  

    while (capacity < initialCapacity)

  4.  

    capacity <<= 1;

这段代码保证初始化时 HashMap 的容量总是 2 的 n 次方,即底层数组的长度总是为 2 的 n 次方。

当 length 总是 2 的 n 次方时,h& (length-1)运算等价于对 length 取模,也就是 h%length,但是 & 比 % 具有更高的效率。这看上去很简单,其实比较有玄机的,我们举个例子来说明:

假设数组长度分别为 15 和 16,优化后的 hash 码分别为 8 和 9,那么 & 运算后的结果如下:

h & (table.length-1) hash   table.length-1  
8 & (15-1): 0100 & 1110 = 0100
9 & (15-1): 0101 & 1110 = 0100
8 & (16-1): 0100 & 1111 = 0100
9 & (16-1): 0101 & 1111 = 0101

从上面的例子中可以看出:当它们和 15-1(1110)“与”的时候,产生了相同的结果,也就是说它们会定位到数组中的同一个位置上去,这就产生了碰撞,8 和 9 会被放到数组中的同一个位置上形成链表,那么查询的时候就需要遍历这个链 表,得到8或者9,这样就降低了查询的效率。同时,我们也可以发现,当数组长度为 15 的时候,hash 值会与 15-1(1110)进行“与”,那么最后一位永远是 0,而 0001,0011,0101,1001,1011,0111,1101 这几个位置永远都不能存放元素了,空间浪费相当大,更糟的是这种情况中,数组可以使用的位置比数组长度小了很多,这意味着进一步增加了碰撞的几率,减慢了查询的效率!而当数组长度为16时,即为2的n次方时,2n-1 得到的二进制数的每个位上的值都为 1,这使得在低位上&时,得到的和原 hash 的低位相同,加之 hash(int h)方法对 key 的 hashCode 的进一步优化,加入了高位计算,就使得只有相同的 hash 值的两个值才会被放到数组中的同一个位置上形成链表。

所以说,当数组长度为 2 的 n 次幂的时候,不同的 key 算得得 index 相同的几率较小,那么数据在数组上分布就比较均匀,也就是说碰撞的几率小,相对的,查询的时候就不用遍历某个位置上的链表,这样查询效率也就较高了。

根据上面 put 方法的源代码可以看出,当程序试图将一个key-value对放入HashMap中时,程序首先根据该 key 的 hashCode() 返回值决定该 Entry 的存储位置:如果两个 Entry 的 key 的 hashCode() 返回值相同,那它们的存储位置相同。如果这两个 Entry 的 key 通过 equals 比较返回 true,新添加 Entry 的 value 将覆盖集合中原有 Entry 的 value,但key不会覆盖。如果这两个 Entry 的 key 通过 equals 比较返回 false,新添加的 Entry 将与集合中原有 Entry 形成 Entry 链,而且新添加的 Entry 位于 Entry 链的头部——具体说明继续看 addEntry() 方法的说明。

读取

  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.  

    * <p>A return value of {@code null} does not <i>necessarily</i>

  11.  

    * indicate that the map contains no mapping for the key; it‘s also

  12.  

    * possible that the map explicitly maps the key to {@code null}.

  13.  

    * The {@link #containsKey containsKey} operation may be used to

  14.  

    * distinguish these two cases.

  15.  

    *

  16.  

    * @see #put(Object, Object)

  17.  

    */

  18.  

    public V get(Object key) {

  19.  

    if (key == null)

  20.  

    return getForNullKey();

  21.  

    Entry<K,V> entry = getEntry(key);

  22.  

  23.  

    return null == entry ? null : entry.getValue();

  24.  

    }

  25.  

    final Entry<K,V> getEntry(Object key) {

  26.  

    int hash = (key == null) ? 0 : hash(key);

  27.  

    for (Entry<K,V> e = table[indexFor(hash, table.length)];

  28.  

    e != null;

  29.  

    e = e.next) {

  30.  

    Object k;

  31.  

    if (e.hash == hash &&

  32.  

    ((k = e.key) == key || (key != null && key.equals(k))))

  33.  

    return e;

  34.  

    }

  35.  

    return null;

  36.  

    }

有了上面存储时的 hash 算法作为基础,理解起来这段代码就很容易了。从上面的源代码中可以看出:从 HashMap 中 get 元素时,首先计算 key 的 hashCode,找到数组中对应位置的某一元素,然后通过 key 的 equals 方法在对应位置的链表中找到需要的元素。

归纳

简单地说,HashMap 在底层将 key-value 当成一个整体进行处理,这个整体就是一个 Entry 对象。HashMap 底层采用一个 Entry[] 数组来保存所有的 key-value 对,当需要存储一个 Entry 对象时,会根据 hash 算法来决定其在数组中的存储位置,在根据 equals 方法决定其在该数组位置上的链表中的存储位置;当需要取出一个Entry 时,也会根据 hash 算法找到其在数组中的存储位置,再根据 equals 方法从该位置上的链表中取出该Entry。

HashMap 的 resize(rehash)

当 HashMap 中的元素越来越多的时候,hash 冲突的几率也就越来越高,因为数组的长度是固定的。所以为了提高查询的效率,就要对 HashMap 的数组进行扩容,数组扩容这个操作也会出现在 ArrayList 中,这是一个常用的操作,而在 HashMap 数组扩容之后,最消耗性能的点就出现了:原数组中的数据必须重新计算其在新数组中的位置,并放进去,这就是 resize。

那么 HashMap 什么时候进行扩容呢?当 HashMap 中的元素个数超过数组大小 *loadFactor时,就会进行数组扩容,loadFactor的默认值为 0.75,这是一个折中的取值。也就是说,默认情况下,数组大小为 16,那么当 HashMap 中元素个数超过 16*0.75=12 的时候,就把数组的大小扩展为 2*16=32,即扩大一倍,然后重新计算每个元素在数组中的位置,而这是一个非常消耗性能的操作,所以如果我们已经预知 HashMap 中元素的个数,那么预设元素的个数能够有效的提高 HashMap 的性能。

HashMap 的性能参数

HashMap 包含如下几个构造器:

  • HashMap():构建一个初始容量为 16,负载因子为 0.75 的 HashMap。
  • ashMap(int initialCapacity):构建一个初始容量为 initialCapacity,负载因子为 0.75 的 HashMap。
  • HashMap(int initialCapacity, float loadFactor):以指定初始容量、指定的负载因子创建一个 HashMap。

HashMap 的基础构造器 HashMap(int initialCapacity, float loadFactor) 带有两个参数,它们是初始容量 initialCapacity 和负载因子 loadFactor。

负载因子 loadFactor 衡量的是一个散列表的空间的使用程度,负载因子越大表示散列表的装填程度越高,反之愈小。对于使用链表法的散列表来说,查找一个元素的平均时间是 O(1+a),因此如果负载因子越大,对空间的利用更充分,然而后果是查找效率的降低;如果负载因子太小,那么散列表的数据将过于稀疏,对空间造成严重浪费。

HashMap 的实现中,通过 threshold 字段来判断 HashMap 的最大容量:

        threshold = (int)(capacity * loadFactor);

结合负载因子的定义公式可知,threshold 就是在此 loadFactor 和 capacity 对应下允许的最大元素数目,超过这个数目就重新 resize,以降低实际的负载因子。默认的的负载因子 0.75 是对空间和时间效率的一个平衡选择。当容量超出此最大容量时, resize 后的 HashMap 容量是容量的两倍:

Fail-Fast 机制

原理

我们知道 java.util.HashMap 不是线程安全的,因此如果在使用迭代器的过程中有其他线程修改了 map,那么将抛出 ConcurrentModificationException,这就是所谓 fail-fast 策略。

ail-fast 机制是 java 集合(Collection)中的一种错误机制。 当多个线程对同一个集合的内容进行操作时,就可能会产生 fail-fast 事件。

例如:当某一个线程 A 通过 iterator去遍历某集合的过程中,若该集合的内容被其他线程所改变了;那么线程 A 访问集合时,就会抛出 ConcurrentModificationException 异常,产生 fail-fast 事件。

这一策略在源码中的实现是通过 modCount 域,modCount 顾名思义就是修改次数,对 HashMap 内容(当然不仅仅是 HashMap 才会有,其他例如 ArrayList 也会)的修改都将增加这个值(大家可以再回头看一下其源码,在很多操作中都有 modCount++ 这句),那么在迭代器初始化过程中会将这个值赋给迭代器的 expectedModCount。

  1. HashIterator() {

  2.  

    expectedModCount = modCount;

  3.  

    if (size > 0) { // advance to first entry

  4.  

    Entry[] t = table;

  5.  

    while (index < t.length && (next = t[index++]) == null)

  6.  

    ;

  7.  

    }

  8.  

    }

在迭代过程中,判断 modCount 跟 expectedModCount 是否相等,如果不相等就表示已经有其他线程修改了 Map:

注意到 modCount 声明为 volatile,保证线程之间修改的可见性。

  1. final Entry<K,V> nextEntry() {

  2.  

    if (modCount != expectedModCount)

  3.  

    throw new ConcurrentModificationException();

在 HashMap 的 API 中指出:

由所有 HashMap 类的“collection 视图方法”所返回的迭代器都是快速失败的:在迭代器创建之后,如果从结构上对映射进行修改,除非通过迭代器本身的 remove 方法,其他任何时间任何方式的修改,迭代器都将抛出 ConcurrentModificationException。因此,面对并发的修改,迭代器很快就会完全失败,而不冒在将来不确定的时间发生任意不确定行为的风险。

注意,迭代器的快速失败行为不能得到保证,一般来说,存在非同步的并发修改时,不可能作出任何坚决的保证。快速失败迭代器尽最大努力抛出 ConcurrentModificationException。因此,编写依赖于此异常的程序的做法是错误的,正确做法是:迭代器的快速失败行为应该仅用于检测程序错误。

解决方案

在上文中也提到,fail-fast 机制,是一种错误检测机制。它只能被用来检测错误,因为 JDK 并不保证 fail-fast 机制一定会发生。若在多线程环境下使用 fail-fast 机制的集合,建议使用“java.util.concurrent 包下的类”去取代“java.util 包下的类”。

HashMap 的两种遍历方式

第一种

  1.   Map map = new HashMap();

  2.  

      Iterator iter = map.entrySet().iterator();

  3.  

      while (iter.hasNext()) {

  4.  

      Map.Entry entry = (Map.Entry) iter.next();

  5.  

      Object key = entry.getKey();

  6.  

      Object val = entry.getValue();

  7.  

      }

效率高,以后一定要使用此种方式!

第二种

  1.   Map map = new HashMap();

  2.  

      Iterator iter = map.keySet().iterator();

  3.  

      while (iter.hasNext()) {

  4.  

      Object key = iter.next();

  5.  

      Object val = map.get(key);

  6.  

      }

效率低,以后尽量少使用!

HashSet 的实现原理

HashSet 概述

对于 HashSet 而言,它是基于 HashMap 实现的,底层采用 HashMap 来保存元素,所以如果对 HashMap 比较熟悉了,那么学习 HashSet 也是很轻松的。

我们先通过 HashSet 最简单的构造函数和几个成员变量来看一下,证明咱们上边说的,其底层是 HashMap:

  1. private transient HashMap<E,Object> map;

  2.  

  3.  

    // Dummy value to associate with an Object in the backing Map

  4.  

    private static final Object PRESENT = new Object();

  5.  

  6.  

    /**

  7.  

    * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has

  8.  

    * default initial capacity (16) and load factor (0.75).

  9.  

    */

  10.  

    public HashSet() {

  11.  

    map = new HashMap<>();

  12.  

    }

其实在英文注释中已经说的比较明确了。首先有一个HashMap的成员变量,我们在 HashSet 的构造函数中将其初始化,默认情况下采用的是 initial capacity为16,load factor 为 0.75。

HashSet 的实现

对于 HashSet 而言,它是基于 HashMap 实现的,HashSet 底层使用 HashMap 来保存所有元素,因此 HashSet 的实现比较简单,相关 HashSet 的操作,基本上都是直接调用底层 HashMap 的相关方法来完成,我们应该为保存到 HashSet 中的对象覆盖 hashCode() 和 equals()

构造方法

  1. /**

  2.  

    * 默认的无参构造器,构造一个空的HashSet。

  3.  

    *

  4.  

    * 实际底层会初始化一个空的HashMap,并使用默认初始容量为16和加载因子0.75。

  5.  

    */

  6.  

    public HashSet() {

  7.  

    map = new HashMap<E,Object>();

  8.  

    }

  9.  

  10.  

    /**

  11.  

    * 构造一个包含指定collection中的元素的新set。

  12.  

    *

  13.  

    * 实际底层使用默认的加载因子0.75和足以包含指定collection中所有元素的初始容量来创建一个HashMap。

  14.  

    * @param c 其中的元素将存放在此set中的collection。

  15.  

    */

  16.  

    public HashSet(Collection<? extends E> c) {

  17.  

    map = new HashMap<E,Object>(Math.max((int) (c.size()/.75f) + 1, 16));

  18.  

    addAll(c);

  19.  

    }

  20.  

  21.  

    /**

  22.  

    * 以指定的initialCapacity和loadFactor构造一个空的HashSet。

  23.  

    *

  24.  

    * 实际底层以相应的参数构造一个空的HashMap。

  25.  

    * @param initialCapacity 初始容量。

  26.  

    * @param loadFactor 加载因子。

  27.  

    */

  28.  

    public HashSet(int initialCapacity, float loadFactor) {

  29.  

    map = new HashMap<E,Object>(initialCapacity, loadFactor);

  30.  

    }

  31.  

  32.  

    /**

  33.  

    * 以指定的initialCapacity构造一个空的HashSet。

  34.  

    *

  35.  

    * 实际底层以相应的参数及加载因子loadFactor为0.75构造一个空的HashMap。

  36.  

    * @param initialCapacity 初始容量。

  37.  

    */

  38.  

    public HashSet(int initialCapacity) {

  39.  

    map = new HashMap<E,Object>(initialCapacity);

  40.  

    }

  41.  

  42.  

    /**

  43.  

    * 以指定的initialCapacity和loadFactor构造一个新的空链接哈希集合。此构造函数为包访问权限,不对外公开,

  44.  

    * 实际只是是对LinkedHashSet的支持。

  45.  

    *

  46.  

    * 实际底层会以指定的参数构造一个空LinkedHashMap实例来实现。

  47.  

    * @param initialCapacity 初始容量。

  48.  

    * @param loadFactor 加载因子。

  49.  

    * @param dummy 标记。

  50.  

    */

  51.  

    HashSet(int initialCapacity, float loadFactor, boolean dummy) {

  52.  

    map = new LinkedHashMap<E,Object>(initialCapacity, loadFactor);

  53.  

    }

add 方法

  1. /**

  2.  

  3.  

    * @param e 将添加到此set中的元素。

  4.  

    * @return 如果此set尚未包含指定元素,则返回true。

  5.  

    */

  6.  

    public boolean add(E e) {

  7.  

    return map.put(e, PRESENT)==null;

  8.  

    }

如果此 set 中尚未包含指定元素,则添加指定元素。更确切地讲,如果此 set 没有包含满足(e==null ? e2==null : e.equals(e2)) 的元素 e2,则向此 set 添加指定的元素 e。如果此 set 已包含该元素,则该调用不更改 set 并返回 false。但底层实际将将该元素作为 key 放入 HashMap。思考一下为什么?

由于 HashMap 的 put() 方法添加 key-value 对时,当新放入 HashMap 的 Entry 中 key 与集合中原有 Entry 的 key 相同(hashCode()返回值相等,通过 equals 比较也返回 true),新添加的 Entry 的 value 会将覆盖原来 Entry 的 value(HashSet 中的 value 都是PRESENT),但 key 不会有任何改变,因此如果向 HashSet 中添加一个已经存在的元素时,新添加的集合元素将不会被放入 HashMap中,原来的元素也不会有任何改变,这也就满足了 Set 中元素不重复的特性。

该方法如果添加的是在 HashSet 中不存在的,则返回 true;如果添加的元素已经存在,返回 false。其原因在于我们之前提到的关于 HashMap 的 put 方法。该方法在添加 key 不重复的键值对的时候,会返回 null。

其余方法

  1. /**

  2.  

    * 如果此set包含指定元素,则返回true。

  3.  

    * 更确切地讲,当且仅当此set包含一个满足(o==null ? e==null : o.equals(e))的e元素时,返回true。

  4.  

    *

  5.  

    * 底层实际调用HashMap的containsKey判断是否包含指定key。

  6.  

    * @param o 在此set中的存在已得到测试的元素。

  7.  

    * @return 如果此set包含指定元素,则返回true。

  8.  

    */

  9.  

    public boolean contains(Object o) {

  10.  

    return map.containsKey(o);

  11.  

    }

  12.  

    /**

  13.  

    * 如果指定元素存在于此set中,则将其移除。更确切地讲,如果此set包含一个满足(o==null ? e==null : o.equals(e))的元素e,

  14.  

    * 则将其移除。如果此set已包含该元素,则返回true

  15.  

    *

  16.  

    * 底层实际调用HashMap的remove方法删除指定Entry。

  17.  

    * @param o 如果存在于此set中则需要将其移除的对象。

  18.  

    * @return 如果set包含指定元素,则返回true。

  19.  

    */

  20.  

    public boolean remove(Object o) {

  21.  

    return map.remove(o)==PRESENT;

  22.  

    }

  23.  

    /**

  24.  

    * 返回此HashSet实例的浅表副本:并没有复制这些元素本身。

  25.  

    *

  26.  

    * 底层实际调用HashMap的clone()方法,获取HashMap的浅表副本,并设置到HashSet中。

  27.  

    */

  28.  

    public Object clone() {

  29.  

    try {

  30.  

    HashSet<E> newSet = (HashSet<E>) super.clone();

  31.  

    newSet.map = (HashMap<E, Object>) map.clone();

  32.  

    return newSet;

  33.  

    } catch (CloneNotSupportedException e) {

  34.  

    throw new InternalError();

  35.  

    }

  36.  

    }

  37.  

    }

相关说明

  1. 相关 HashMap 的实现原理,请参考我的上一遍总结:HashMap的实现原理
  2. 对于 HashSet 中保存的对象,请注意正确重写其 equals 和 hashCode 方法,以保证放入的对象的唯一性。这两个方法是比较重要的,希望大家在以后的开发过程中需要注意一下。

Hashtable 的实现原理

概述

和 HashMap 一样,Hashtable 也是一个散列表,它存储的内容是键值对。

Hashtable 在 Java 中的定义为:

  1. public class Hashtable<K,V>

  2.  

    extends Dictionary<K,V>

  3.  

    implements Map<K,V>, Cloneable, java.io.Serializable{}

从源码中,我们可以看出,Hashtable 继承于 Dictionary 类,实现了 Map, Cloneable, java.io.Serializable接口。其中Dictionary类是任何可将键映射到相应值的类(如 Hashtable)的抽象父类,每个键和值都是对象(源码注释为:The Dictionary class is the abstract parent of any class, such as Hashtable, which maps keys to values. Every key and every value is an object.)。但在这一点我开始有点怀疑,因为我查看了HashMap以及TreeMap的源码,都没有继承于这个类。不过当我看到注释中的解释也就明白了,其 Dictionary 源码注释是这样的:NOTE: This class is obsolete. New implementations should implement the Map interface, rather than extending this class. 该话指出 Dictionary 这个类过时了,新的实现类应该实现Map接口。

Hashtable 源码解读

成员变量

Hashtable是通过"拉链法"实现的哈希表。它包括几个重要的成员变量:table, count, threshold, loadFactor, modCount。

  • table是一个 Entry[] 数组类型,而 Entry(在 HashMap 中有讲解过)实际上就是一个单向链表。哈希表的"key-value键值对"都是存储在Entry数组中的。
  • count 是 Hashtable 的大小,它是 Hashtable 保存的键值对的数量。
  • threshold 是 Hashtable 的阈值,用于判断是否需要调整 Hashtable 的容量。threshold 的值="容量*加载因子"。
  • loadFactor 就是加载因子。
  • modCount 是用来实现 fail-fast 机制的。

关于变量的解释在源码注释中都有,最好还是应该看英文注释。

  1. /**

  2.  

    * The hash table data.

  3.  

    */

  4.  

    private transient Entry<K,V>[] table;

  5.  

  6.  

    /**

  7.  

    * The total number of entries in the hash table.

  8.  

    */

  9.  

    private transient int count;

  10.  

  11.  

    /**

  12.  

    * The table is rehashed when its size exceeds this threshold. (The

  13.  

    * value of this field is (int)(capacity * loadFactor).)

  14.  

    *

  15.  

    * @serial

  16.  

    */

  17.  

    private int threshold;

  18.  

  19.  

    /**

  20.  

    * The load factor for the hashtable.

  21.  

    *

  22.  

    * @serial

  23.  

    */

  24.  

    private float loadFactor;

  25.  

  26.  

    /**

  27.  

    * The number of times this Hashtable has been structurally modified

  28.  

    * Structural modifications are those that change the number of entries in

  29.  

    * the Hashtable or otherwise modify its internal structure (e.g.,

  30.  

    * rehash). This field is used to make iterators on Collection-views of

  31.  

    * the Hashtable fail-fast. (See ConcurrentModificationException).

  32.  

    */

  33.  

    private transient int modCount = 0;

构造方法

Hashtable 一共提供了 4 个构造方法:

  • public Hashtable(int initialCapacity, float loadFactor): 用指定初始容量和指定加载因子构造一个新的空哈希表。useAltHashing 为 boolean,其如果为真,则执行另一散列的字符串键,以减少由于弱哈希计算导致的哈希冲突的发生。
  • public Hashtable(int initialCapacity):用指定初始容量和默认的加载因子 (0.75) 构造一个新的空哈希表。
  • public Hashtable():默认构造函数,容量为 11,加载因子为 0.75。
  • public Hashtable(Map<? extends K, ? extends V> t):构造一个与给定的 Map 具有相同映射关系的新哈希表。
  1. /**

  2.  

    * Constructs a new, empty hashtable with the specified initial

  3.  

    * capacity and the specified load factor.

  4.  

    *

  5.  

    * @param initialCapacity the initial capacity of the hashtable.

  6.  

    * @param loadFactor the load factor of the hashtable.

  7.  

    * @exception IllegalArgumentException if the initial capacity is less

  8.  

    * than zero, or if the load factor is nonpositive.

  9.  

    */

  10.  

    public Hashtable(int initialCapacity, float loadFactor) {

  11.  

    if (initialCapacity < 0)

  12.  

    throw new IllegalArgumentException("Illegal Capacity: "+

  13.  

    initialCapacity);

  14.  

    if (loadFactor <= 0 || Float.isNaN(loadFactor))

  15.  

    throw new IllegalArgumentException("Illegal Load: "+loadFactor);

  16.  

  17.  

    if (initialCapacity==0)

  18.  

    initialCapacity = 1;

  19.  

    this.loadFactor = loadFactor;

  20.  

    table = new Entry[initialCapacity];

  21.  

    threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);

  22.  

    useAltHashing = sun.misc.VM.isBooted() &&

  23.  

    (initialCapacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);

  24.  

    }

  25.  

  26.  

    /**

  27.  

    * Constructs a new, empty hashtable with the specified initial capacity

  28.  

    * and default load factor (0.75).

  29.  

    *

  30.  

    * @param initialCapacity the initial capacity of the hashtable.

  31.  

    * @exception IllegalArgumentException if the initial capacity is less

  32.  

    * than zero.

  33.  

    */

  34.  

    public Hashtable(int initialCapacity) {

  35.  

    this(initialCapacity, 0.75f);

  36.  

    }

  37.  

  38.  

    /**

  39.  

    * Constructs a new, empty hashtable with a default initial capacity (11)

  40.  

    * and load factor (0.75).

  41.  

    */

  42.  

    public Hashtable() {

  43.  

    this(11, 0.75f);

  44.  

    }

  45.  

  46.  

    /**

  47.  

    * Constructs a new hashtable with the same mappings as the given

  48.  

    * Map. The hashtable is created with an initial capacity sufficient to

  49.  

    * hold the mappings in the given Map and a default load factor (0.75).

  50.  

    *

  51.  

    * @param t the map whose mappings are to be placed in this map.

  52.  

    * @throws NullPointerException if the specified map is null.

  53.  

    * @since 1.2

  54.  

    */

  55.  

    public Hashtable(Map<? extends K, ? extends V> t) {

  56.  

    this(Math.max(2*t.size(), 11), 0.75f);

  57.  

    putAll(t);

  58.  

    }

put 方法

put 方法的整个流程为:

  1. 判断 value 是否为空,为空则抛出异常;
  2. 计算 key 的 hash 值,并根据 hash 值获得 key 在 table 数组中的位置 index,如果 table[index] 元素不为空,则进行迭代,如果遇到相同的 key,则直接替换,并返回旧 value;
  3. 否则,我们可以将其插入到 table[index] 位置。

我在下面的代码中也进行了一些注释:

  1. public synchronized V put(K key, V value) {

  2.  

    // Make sure the value is not null确保value不为null

  3.  

    if (value == null) {

  4.  

    throw new NullPointerException();

  5.  

    }

  6.  

  7.  

    // Makes sure the key is not already in the hashtable.

  8.  

    //确保key不在hashtable中

  9.  

    //首先,通过hash方法计算key的哈希值,并计算得出index值,确定其在table[]中的位置

  10.  

    //其次,迭代index索引位置的链表,如果该位置处的链表存在相同的key,则替换value,返回旧的value

  11.  

    Entry tab[] = table;

  12.  

    int hash = hash(key);

  13.  

    int index = (hash & 0x7FFFFFFF) % tab.length;

  14.  

    for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {

  15.  

    if ((e.hash == hash) && e.key.equals(key)) {

  16.  

    V old = e.value;

  17.  

    e.value = value;

  18.  

    return old;

  19.  

    }

  20.  

    }

  21.  

  22.  

    modCount++;

  23.  

    if (count >= threshold) {

  24.  

    // Rehash the table if the threshold is exceeded

  25.  

    //如果超过阀值,就进行rehash操作

  26.  

    rehash();

  27.  

  28.  

    tab = table;

  29.  

    hash = hash(key);

  30.  

    index = (hash & 0x7FFFFFFF) % tab.length;

  31.  

    }

  32.  

  33.  

    // Creates the new entry.

  34.  

    //将值插入,返回的为null

  35.  

    Entry<K,V> e = tab[index];

  36.  

    // 创建新的Entry节点,并将新的Entry插入Hashtable的index位置,并设置e为新的Entry的下一个元素

  37.  

    tab[index] = new Entry<>(hash, key, value, e);

  38.  

    count++;

  39.  

    return null;

  40.  

    }

通过一个实际的例子来演示一下这个过程:

假设我们现在Hashtable的容量为5,已经存在了(5,5),(13,13),(16,16),(17,17),(21,21)这 5 个键值对,目前他们在Hashtable中的位置如下:

现在,我们插入一个新的键值对,put(16,22),假设key=16的索引为1.但现在索引1的位置有两个Entry了,所以程序会对链表进行迭代。迭代的过程中,发现其中有一个Entry的key和我们要插入的键值对的key相同,所以现在会做的工作就是将newValue=22替换oldValue=16,然后返回oldValue=16.

然后我们现在再插入一个,put(33,33),key=33的索引为3,并且在链表中也不存在key=33的Entry,所以将该节点插入链表的第一个位置。

get 方法

相比较于 put 方法,get 方法则简单很多。其过程就是首先通过 hash()方法求得 key 的哈希值,然后根据 hash 值得到 index 索引(上述两步所用的算法与 put 方法都相同)。然后迭代链表,返回匹配的 key 的对应的 value;找不到则返回 null。

  1. public synchronized V get(Object key) {

  2.  

    Entry tab[] = table;

  3.  

    int hash = hash(key);

  4.  

    int index = (hash & 0x7FFFFFFF) % tab.length;

  5.  

    for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {

  6.  

    if ((e.hash == hash) && e.key.equals(key)) {

  7.  

    return e.value;

  8.  

    }

  9.  

    }

  10.  

    return null;

  11.  

    }

Hashtable 遍历方式

Hashtable 有多种遍历方式:

  1. //1、使用keys()

  2.  

    Enumeration<String> en1 = table.keys();

  3.  

    while(en1.hasMoreElements()) {

  4.  

    en1.nextElement();

  5.  

    }

  6.  

  7.  

    //2、使用elements()

  8.  

    Enumeration<String> en2 = table.elements();

  9.  

    while(en2.hasMoreElements()) {

  10.  

    en2.nextElement();

  11.  

    }

  12.  

  13.  

    //3、使用keySet()

  14.  

    Iterator<String> it1 = table.keySet().iterator();

  15.  

    while(it1.hasNext()) {

  16.  

    it1.next();

  17.  

    }

  18.  

  19.  

    //4、使用entrySet()

  20.  

    Iterator<Entry<String, String>> it2 = table.entrySet().iterator();

  21.  

    while(it2.hasNext()) {

  22.  

    it2.next();

  23.  

    }

Hashtable 与 HashMap 的简单比较

  1. HashTable 基于 Dictionary 类,而 HashMap 是基于 AbstractMap。Dictionary 是任何可将键映射到相应值的类的抽象父类,而 AbstractMap 是基于 Map 接口的实现,它以最大限度地减少实现此接口所需的工作。
  2. HashMap 的 key 和 value 都允许为 null,而 Hashtable 的 key 和 value 都不允许为 null。HashMap 遇到 key 为 null 的时候,调用 putForNullKey 方法进行处理,而对 value 没有处理;Hashtable遇到 null,直接返回 NullPointerException。
  3. Hashtable 方法是同步,而HashMap则不是。我们可以看一下源码,Hashtable 中的几乎所有的 public 的方法都是 synchronized 的,而有些方法也是在内部通过 synchronized 代码块来实现。所以有人一般都建议如果是涉及到多线程同步时采用 HashTable,没有涉及就采用 HashMap,但是在 Collections 类中存在一个静态方法:synchronizedMap(),该方法创建了一个线程安全的 Map 对象,并把它作为一个封装的对象来返回。

LinkedHashMap 的实现原理

LinkedHashMap 概述

HashMap 是无序的,HashMap 在 put 的时候是根据 key 的 hashcode 进行 hash 然后放入对应的地方。所以在按照一定顺序 put 进 HashMap 中,然后遍历出 HashMap 的顺序跟 put 的顺序不同(除非在 put 的时候 key 已经按照 hashcode 排序号了,这种几率非常小)

JAVA 在 JDK1.4 以后提供了 LinkedHashMap 来帮助我们实现了有序的 HashMap!

LinkedHashMap 是 HashMap 的一个子类,它保留插入的顺序,如果需要输出的顺序和输入时的相同,那么就选用 LinkedHashMap。

LinkedHashMap 是 Map 接口的哈希表和链接列表实现,具有可预知的迭代顺序。此实现提供所有可选的映射操作,并允许使用 null 值和 null 键。此类不保证映射的顺序,特别是它不保证该顺序恒久不变。

LinkedHashMap 实现与 HashMap 的不同之处在于,LinkedHashMap 维护着一个运行于所有条目的双重链接列表。此链接列表定义了迭代顺序,该迭代顺序可以是插入顺序或者是访问顺序。

注意,此实现不是同步的。如果多个线程同时访问链接的哈希映射,而其中至少一个线程从结构上修改了该映射,则它必须保持外部同步。

根据链表中元素的顺序可以分为:按插入顺序的链表,和按访问顺序(调用 get 方法)的链表。默认是按插入顺序排序,如果指定按访问顺序排序,那么调用get方法后,会将这次访问的元素移至链表尾部,不断访问可以形成按访问顺序排序的链表。

小 Demo

我在最开始学习 LinkedHashMap 的时候,看到访问顺序、插入顺序等等,有点晕了,随着后续的学习才慢慢懂得其中原理,所以我会先在进行做几个 demo 来演示一下 LinkedHashMap 的使用。看懂了其效果,然后再来研究其原理。

HashMap

看下面这个代码:

  1. public static void main(String[] args) {

  2.  

    Map<String, String> map = new HashMap<String, String>();

  3.  

    map.put("apple", "苹果");

  4.  

    map.put("watermelon", "西瓜");

  5.  

    map.put("banana", "香蕉");

  6.  

    map.put("peach", "桃子");

  7.  

  8.  

    Iterator iter = map.entrySet().iterator();

  9.  

    while (iter.hasNext()) {

  10.  

    Map.Entry entry = (Map.Entry) iter.next();

  11.  

    System.out.println(entry.getKey() + "=" + entry.getValue());

  12.  

    }

  13.  

    }

一个比较简单的测试 HashMap 的代码,通过控制台的输出,我们可以看到 HashMap 是没有顺序的。

  1. banana=香蕉

  2.  

    apple=苹果

  3.  

    peach=桃子

  4.  

    watermelon=西瓜

LinkedHashMap

我们现在将 map 的实现换成 LinkedHashMap,其他代码不变:Map<String, String> map = new LinkedHashMap<String, String>();

看一下控制台的输出:

  1. apple=苹果

  2.  

    watermelon=西瓜

  3.  

    banana=香蕉

  4.  

    peach=桃子

我们可以看到,其输出顺序是完成按照插入顺序的!也就是我们上面所说的保留了插入的顺序。我们不是在上面还提到过其可以按照访问顺序进行排序么?好的,我们还是通过一个例子来验证一下:

  1. public static void main(String[] args) {

  2.  

    Map<String, String> map = new LinkedHashMap<String, String>(16,0.75f,true);

  3.  

    map.put("apple", "苹果");

  4.  

    map.put("watermelon", "西瓜");

  5.  

    map.put("banana", "香蕉");

  6.  

    map.put("peach", "桃子");

  7.  

  8.  

    map.get("banana");

  9.  

    map.get("apple");

  10.  

  11.  

    Iterator iter = map.entrySet().iterator();

  12.  

    while (iter.hasNext()) {

  13.  

    Map.Entry entry = (Map.Entry) iter.next();

  14.  

    System.out.println(entry.getKey() + "=" + entry.getValue());

  15.  

    }

  16.  

    }

代码与之前的都差不多,但我们多了两行代码,并且初始化 LinkedHashMap 的时候,用的构造函数也不相同,看一下控制台的输出结果:

  1. watermelon=西瓜

  2.  

    peach=桃子

  3.  

    banana=香蕉

  4.  

    apple=苹果

这也就是我们之前提到过的,LinkedHashMap 可以选择按照访问顺序进行排序。

LinkedHashMap 的实现

对于 LinkedHashMap 而言,它继承与 HashMap(public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>)、底层使用哈希表与双向链表来保存所有元素。其基本操作与父类 HashMap 相似,它通过重写父类相关的方法,来实现自己的链接列表特性。下面我们来分析 LinkedHashMap 的源代码:

成员变量

LinkedHashMap 采用的 hash 算法和 HashMap 相同,但是它重新定义了数组中保存的元素 Entry,该 Entry 除了保存当前对象的引用外,还保存了其上一个元素 before 和下一个元素 after 的引用,从而在哈希表的基础上又构成了双向链接列表。看源代码:

  1. /**

  2.  

    * The iteration ordering method for this linked hash map: <tt>true</tt>

  3.  

    * for access-order, <tt>false</tt> for insertion-order.

  4.  

    * 如果为true,则按照访问顺序;如果为false,则按照插入顺序。

  5.  

    */

  6.  

    private final boolean accessOrder;

  7.  

    /**

  8.  

    * 双向链表的表头元素。

  9.  

    */

  10.  

    private transient Entry<K,V> header;

  11.  

  12.  

    /**

  13.  

    * LinkedHashMap的Entry元素。

  14.  

    * 继承HashMap的Entry元素,又保存了其上一个元素before和下一个元素after的引用。

  15.  

    */

  16.  

    private static class Entry<K,V> extends HashMap.Entry<K,V> {

  17.  

    Entry<K,V> before, after;

  18.  

    ……

  19.  

    }

LinkedHashMap 中的 Entry 集成与 HashMap 的 Entry,但是其增加了 before 和 after 的引用,指的是上一个元素和下一个元素的引用。

初始化

通过源代码可以看出,在 LinkedHashMap 的构造方法中,实际调用了父类 HashMap 的相关构造方法来构造一个底层存放的 table 数组,但额外可以增加 accessOrder 这个参数,如果不设置,默认为 false,代表按照插入顺序进行迭代;当然可以显式设置为 true,代表以访问顺序进行迭代。如:

  1. public LinkedHashMap(int initialCapacity, float loadFactor,boolean accessOrder) {

  2.  

    super(initialCapacity, loadFactor);

  3.  

    this.accessOrder = accessOrder;

  4.  

    }

我们已经知道 LinkedHashMap 的 Entry 元素继承 HashMap 的 Entry,提供了双向链表的功能。在上述 HashMap 的构造器中,最后会调用 init() 方法,进行相关的初始化,这个方法在 HashMap 的实现中并无意义,只是提供给子类实现相关的初始化调用。

但在 LinkedHashMap 重写了 init() 方法,在调用父类的构造方法完成构造后,进一步实现了对其元素 Entry 的初始化操作。

  1. /**

  2.  

    * Called by superclass constructors and pseudoconstructors (clone,

  3.  

    * readObject) before any entries are inserted into the map. Initializes

  4.  

    * the chain.

  5.  

    */

  6.  

    @Override

  7.  

    void init() {

  8.  

    header = new Entry<>(-1, null, null, null);

  9.  

    header.before = header.after = header;

  10.  

    }

存储

LinkedHashMap 并未重写父类 HashMap 的 put 方法,而是重写了父类 HashMap 的 put 方法调用的子方法void recordAccess(HashMap m) ,void addEntry(int hash, K key, V value, int bucketIndex) 和void createEntry(int hash, K key, V value, int bucketIndex),提供了自己特有的双向链接列表的实现。我们在之前的文章中已经讲解了HashMap的put方法,我们在这里重新贴一下 HashMap 的 put 方法的源代码:

HashMap.put:

  1. public V put(K key, V value) {

  2.  

    if (key == null)

  3.  

    return putForNullKey(value);

  4.  

    int hash = hash(key);

  5.  

    int i = indexFor(hash, table.length);

  6.  

    for (Entry<K,V> e = table[i]; e != null; e = e.next) {

  7.  

    Object k;

  8.  

    if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {

  9.  

    V oldValue = e.value;

  10.  

    e.value = value;

  11.  

    e.recordAccess(this);

  12.  

    return oldValue;

  13.  

    }

  14.  

    }

  15.  

  16.  

    modCount++;

  17.  

    addEntry(hash, key, value, i);

  18.  

    return null;

  19.  

    }

重写方法:

  1. void recordAccess(HashMap<K,V> m) {

  2.  

    LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m;

  3.  

    if (lm.accessOrder) {

  4.  

    lm.modCount++;

  5.  

    remove();

  6.  

    addBefore(lm.header);

  7.  

    }

  8.  

    }

  9.  

  10.  

    void addEntry(int hash, K key, V value, int bucketIndex) {

  11.  

    // 调用create方法,将新元素以双向链表的的形式加入到映射中。

  12.  

    createEntry(hash, key, value, bucketIndex);

  13.  

  14.  

    // 删除最近最少使用元素的策略定义

  15.  

    Entry<K,V> eldest = header.after;

  16.  

    if (removeEldestEntry(eldest)) {

  17.  

    removeEntryForKey(eldest.key);

  18.  

    } else {

  19.  

    if (size >= threshold)

  20.  

    resize(2 * table.length);

  21.  

    }

  22.  

    }

  23.  

  24.  

    void createEntry(int hash, K key, V value, int bucketIndex) {

  25.  

    HashMap.Entry<K,V> old = table[bucketIndex];

  26.  

    Entry<K,V> e = new Entry<K,V>(hash, key, value, old);

  27.  

    table[bucketIndex] = e;

  28.  

    // 调用元素的addBrefore方法,将元素加入到哈希、双向链接列表。

  29.  

    e.addBefore(header);

  30.  

    size++;

  31.  

    }

  32.  

  33.  

    private void addBefore(Entry<K,V> existingEntry) {

  34.  

    after = existingEntry;

  35.  

    before = existingEntry.before;

  36.  

    before.after = this;

  37.  

    after.before = this;

  38.  

    }

读取

LinkedHashMap 重写了父类 HashMap 的 get 方法,实际在调用父类 getEntry() 方法取得查找的元素后,再判断当排序模式 accessOrder 为 true 时,记录访问顺序,将最新访问的元素添加到双向链表的表头,并从原来的位置删除。由于的链表的增加、删除操作是常量级的,故并不会带来性能的损失。

  1. public V get(Object key) {

  2.  

    // 调用父类HashMap的getEntry()方法,取得要查找的元素。

  3.  

    Entry<K,V> e = (Entry<K,V>)getEntry(key);

  4.  

    if (e == null)

  5.  

    return null;

  6.  

    // 记录访问顺序。

  7.  

    e.recordAccess(this);

  8.  

    return e.value;

  9.  

    }

  10.  

  11.  

    void recordAccess(HashMap<K,V> m) {

  12.  

    LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m;

  13.  

    // 如果定义了LinkedHashMap的迭代顺序为访问顺序,

  14.  

    // 则删除以前位置上的元素,并将最新访问的元素添加到链表表头。

  15.  

    if (lm.accessOrder) {

  16.  

    lm.modCount++;

  17.  

    remove();

  18.  

    addBefore(lm.header);

  19.  

    }

  20.  

    }

  21.  

  22.  

    /**

  23.  

    * Removes this entry from the linked list.

  24.  

    */

  25.  

    private void remove() {

  26.  

    before.after = after;

  27.  

    after.before = before;

  28.  

    }

  29.  

  30.  

    /**clear链表,设置header为初始状态*/

  31.  

    public void clear() {

  32.  

    super.clear();

  33.  

    header.before = header.after = header;

  34.  

    }

排序模式

LinkedHashMap 定义了排序模式 accessOrder,该属性为 boolean 型变量,对于访问顺序,为 true;对于插入顺序,则为 false。一般情况下,不必指定排序模式,其迭代顺序即为默认为插入顺序。

这些构造方法都会默认指定排序模式为插入顺序。如果你想构造一个 LinkedHashMap,并打算按从近期访问最少到近期访问最多的顺序(即访问顺序)来保存元素,那么请使用下面的构造方法构造 LinkedHashMap:public LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)

该哈希映射的迭代顺序就是最后访问其条目的顺序,这种映射很适合构建 LRU 缓存。LinkedHashMap 提供了 removeEldestEntry(Map.Entry<K,V> eldest) 方法。该方法可以提供在每次添加新条目时移除最旧条目的实现程序,默认返回 false,这样,此映射的行为将类似于正常映射,即永远不能移除最旧的元素。

我们会在后面的文章中详细介绍关于如何用 LinkedHashMap 构建 LRU 缓存。

总结

其实 LinkedHashMap 几乎和 HashMap 一样:从技术上来说,不同的是它定义了一个 Entry<K,V> header,这个 header 不是放在 Table 里,它是额外独立出来的。LinkedHashMap 通过继承 hashMap 中的 Entry<K,V>,并添加两个属性 Entry<K,V> before,after,和 header 结合起来组成一个双向链表,来实现按插入顺序或访问顺序排序。

在写关于 LinkedHashMap 的过程中,记起来之前面试的过程中遇到的一个问题,也是问我 Map 的哪种实现可以做到按照插入顺序进行迭代?当时脑子是突然短路的,但现在想想,也只能怪自己对这个知识点还是掌握的不够扎实,所以又从头认真的把代码看了一遍。

不过,我的建议是,大家首先首先需要记住的是:LinkedHashMap 能够做到按照插入顺序或者访问顺序进行迭代,这样在我们以后的开发中遇到相似的问题,才能想到用 LinkedHashMap 来解决,否则就算对其内部结构非常了解,不去使用也是没有什么用的。

LinkedHashSet 的实现原理

LinkedHashSet 概述

思考了好久,到底要不要总结 LinkedHashSet 的内容 = = 我在之前的博文中,分别写了 HashMap 和 HashSet,然后我们可以看到 HashSet 的方法基本上都是基于 HashMap 来实现的,说白了,HashSet内部的数据结构就是一个 HashMap,其方法的内部几乎就是在调用 HashMap 的方法。

LinkedHashSet 首先我们需要知道的是它是一个 Set 的实现,所以它其中存的肯定不是键值对,而是值。此实现与 HashSet 的不同之处在于,LinkedHashSet 维护着一个运行于所有条目的双重链接列表。此链接列表定义了迭代顺序,该迭代顺序可为插入顺序或是访问顺序。

看到上面的介绍,是不是感觉其与 HashMap 和 LinkedHashMap 的关系很像?

注意,此实现不是同步的。如果多个线程同时访问链接的哈希Set,而其中至少一个线程修改了该 Set,则它必须保持外部同步。

小 Demo

LinkedHashMap的实现原理中,通过例子演示了 HashMap 和 LinkedHashMap 的区别。举一反三,我们现在学习的LinkedHashSet与之前的很相同,只不过之前存的是键值对,而现在存的只有值。

所以我就不再具体的贴代码在这边了,但我们可以肯定的是,LinkedHashSet 是可以按照插入顺序或者访问顺序进行迭代。

LinkedHashSet 的实现

对于 LinkedHashSet 而言,它继承与 HashSet、又基于 LinkedHashMap 来实现的。

LinkedHashSet 底层使用 LinkedHashMap 来保存所有元素,它继承与 HashSet,其所有的方法操作上又与 HashSet 相同,因此 LinkedHashSet 的实现上非常简单,只提供了四个构造方法,并通过传递一个标识参数,调用父类的构造器,底层构造一个 LinkedHashMap 来实现,在相关操作上与父类 HashSet 的操作相同,直接调用父类 HashSet 的方法即可。LinkedHashSet 的源代码如下:

  1. public class LinkedHashSet<E>

  2.  

    extends HashSet<E>

  3.  

    implements Set<E>, Cloneable, java.io.Serializable {

  4.  

  5.  

    private static final long serialVersionUID = -2851667679971038690L;

  6.  

  7.  

    /**

  8.  

    * 构造一个带有指定初始容量和加载因子的新空链接哈希set。

  9.  

    *

  10.  

    * 底层会调用父类的构造方法,构造一个有指定初始容量和加载因子的LinkedHashMap实例。

  11.  

    * @param initialCapacity 初始容量。

  12.  

    * @param loadFactor 加载因子。

  13.  

    */

  14.  

    public LinkedHashSet(int initialCapacity, float loadFactor) {

  15.  

    super(initialCapacity, loadFactor, true);

  16.  

    }

  17.  

  18.  

    /**

  19.  

    * 构造一个带指定初始容量和默认加载因子0.75的新空链接哈希set。

  20.  

    *

  21.  

    * 底层会调用父类的构造方法,构造一个带指定初始容量和默认加载因子0.75的LinkedHashMap实例。

  22.  

    * @param initialCapacity 初始容量。

  23.  

    */

  24.  

    public LinkedHashSet(int initialCapacity) {

  25.  

    super(initialCapacity, .75f, true);

  26.  

    }

  27.  

  28.  

    /**

  29.  

    * 构造一个带默认初始容量16和加载因子0.75的新空链接哈希set。

  30.  

    *

  31.  

    * 底层会调用父类的构造方法,构造一个带默认初始容量16和加载因子0.75的LinkedHashMap实例。

  32.  

    */

  33.  

    public LinkedHashSet() {

  34.  

    super(16, .75f, true);

  35.  

    }

  36.  

  37.  

    /**

  38.  

    * 构造一个与指定collection中的元素相同的新链接哈希set。

  39.  

    *

  40.  

    * 底层会调用父类的构造方法,构造一个足以包含指定collection

  41.  

    * 中所有元素的初始容量和加载因子为0.75的LinkedHashMap实例。

  42.  

    * @param c 其中的元素将存放在此set中的collection。

  43.  

    */

  44.  

    public LinkedHashSet(Collection<? extends E> c) {

  45.  

    super(Math.max(2*c.size(), 11), .75f, true);

  46.  

    addAll(c);

  47.  

    }

  48.  

    }

以上几乎就是 LinkedHashSet 的全部代码了,那么读者可能就会怀疑了,不是说 LinkedHashSet 是基于 LinkedHashMap 实现的吗?那我为什么在源码中甚至都没有看到出现过 LinkedHashMap。不要着急,我们可以看到在 LinkedHashSet 的构造方法中,其调用了父类的构造方法。我们可以进去看一下:

  1. /**

  2.  

    * 以指定的initialCapacity和loadFactor构造一个新的空链接哈希集合。

  3.  

    * 此构造函数为包访问权限,不对外公开,实际只是是对LinkedHashSet的支持。

  4.  

    *

  5.  

    * 实际底层会以指定的参数构造一个空LinkedHashMap实例来实现。

  6.  

    * @param initialCapacity 初始容量。

  7.  

    * @param loadFactor 加载因子。

  8.  

    * @param dummy 标记。

  9.  

    */

  10.  

    HashSet(int initialCapacity, float loadFactor, boolean dummy) {

  11.  

    map = new LinkedHashMap<E,Object>(initialCapacity, loadFactor);

  12.  

    }

在父类 HashSet 中,专为 LinkedHashSet 提供的构造方法如下,该方法为包访问权限,并未对外公开。

由上述源代码可见,LinkedHashSet 通过继承 HashSet,底层使用 LinkedHashMap,以很简单明了的方式来实现了其自身的所有功能。

总结

以上就是关于 LinkedHashSet 的内容,我们只是从概述上以及构造方法这几个方面介绍了,并不是我们不想去深入其读取或者写入方法,而是其本身没有实现,只是继承于父类 HashSet 的方法。

所以我们需要注意的点是:

  • LinkedHashSet 是 Set 的一个具体实现,其维护着一个运行于所有条目的双重链接列表。此链接列表定义了迭代顺序,该迭代顺序可为插入顺序或是访问顺序。
  • LinkedHashSet 继承与 HashSet,并且其内部是通过 LinkedHashMap 来实现的。有点类似于我们之前说的LinkedHashMap 其内部是基于 Hashmap 实现一样,不过还是有一点点区别的(具体的区别大家可以自己去思考一下)。
  • 如果我们需要迭代的顺序为插入顺序或者访问顺序,那么 LinkedHashSet 是需要你首先考虑的。

ArrayList 的实现原理

ArrayList 概述

ArrayList 可以理解为动态数组,用 MSDN 中的说法,就是 Array 的复杂版本。与 Java 中的数组相比,它的容量能动态增长。ArrayList 是 List 接口的可变数组的实现。实现了所有可选列表操作,并允许包括 null 在内的所有元素。除了实现 List 接口外,此类还提供一些方法来操作内部用来存储列表的数组的大小。(此类大致上等同于 Vector 类,除了此类是不同步的。)

每个 ArrayList 实例都有一个容量,该容量是指用来存储列表元素的数组的大小。它总是至少等于列表的大小。随着向 ArrayList 中不断添加元素,其容量也自动增长。自动增长会带来数据向新数组的重新拷贝,因此,如果可预知数据量的多少,可在构造 ArrayList 时指定其容量。在添加大量元素前,应用程序也可以使用 ensureCapacity 操作来增加 ArrayList 实例的容量,这可以减少递增式再分配的数量。

注意,此实现不是同步的。如果多个线程同时访问一个 ArrayList 实例,而其中至少一个线程从结构上修改了列表,那么它必须保持外部同步。(结构上的修改是指任何添加或删除一个或多个元素的操作,或者显式调整底层数组的大小;仅仅设置元素的值不是结构上的修改。)

我们先学习了解其内部的实现原理,才能更好的理解其应用。

ArrayList 的实现

对于 ArrayList 而言,它实现 List 接口、底层使用数组保存所有元素。其操作基本上是对数组的操作。下面我们来分析 ArrayList 的源代码:

实现的接口

  1. public class ArrayList<E> extends AbstractList<E>

  2.  

    implements List<E>, RandomAccess, Cloneable, java.io.Serializable

  3.  

    {

  4.  

    }

ArrayList 继承了 AbstractList,实现了 List。它是一个数组队列,提供了相关的添加、删除、修改、遍历等功能。

ArrayList 实现了 RandmoAccess 接口,即提供了随机访问功能。RandmoAccess 是 java 中用来被 List 实现,为 List 提供快速访问功能的。在 ArrayList 中,我们即可以通过元素的序号快速获取元素对象;这就是快速随机访问。

ArrayList 实现了 Cloneable 接口,即覆盖了函数 clone(),能被克隆。 ArrayList 实现 java.io.Serializable 接口,这意味着 ArrayList 支持序列化,能通过序列化去传输。

底层使用数组实现

  1. /**

  2.  

    * The array buffer into which the elements of the ArrayList are stored.

  3.  

    * The capacity of the ArrayList is the length of this array buffer.

  4.  

    */

  5.  

    private transient Object[] elementData;

构造方法

  1.  

    /**

  2.  

    * Constructs an empty list with an initial capacity of ten.

  3.  

    */

  4.  

    public ArrayList() {

  5.  

    this(10);

  6.  

    }

  7.  

    /**

  8.  

    * Constructs an empty list with the specified initial capacity.

  9.  

    *

  10.  

    * @param initialCapacity the initial capacity of the list

  11.  

    * @throws IllegalArgumentException if the specified initial capacity

  12.  

    * is negative

  13.  

    */

  14.  

    public ArrayList(int initialCapacity) {

  15.  

    super();

  16.  

    if (initialCapacity < 0)

  17.  

    throw new IllegalArgumentException("Illegal Capacity: "+

  18.  

    initialCapacity);

  19.  

    this.elementData = new Object[initialCapacity];

  20.  

    }

  21.  

  22.  

    /**

  23.  

    * Constructs a list containing the elements of the specified

  24.  

    * collection, in the order they are returned by the collection‘s

  25.  

    * iterator.

  26.  

    *

  27.  

    * @param c the collection whose elements are to be placed into this list

  28.  

    * @throws NullPointerException if the specified collection is null

  29.  

    */

  30.  

    public ArrayList(Collection<? extends E> c) {

  31.  

    elementData = c.toArray();

  32.  

    size = elementData.length;

  33.  

    // c.toArray might (incorrectly) not return Object[] (see 6260652)

  34.  

    if (elementData.getClass() != Object[].class)

  35.  

    elementData = Arrays.copyOf(elementData, size, Object[].class);

  36.  

    }

ArrayList 提供了三种方式的构造器:

  1. public ArrayList()可以构造一个默认初始容量为10的空列表;
  2. public ArrayList(int initialCapacity)构造一个指定初始容量的空列表;
  3. public ArrayList(Collection<? extends E> c)构造一个包含指定 collection 的元素的列表,这些元素按照该collection的迭代器返回它们的顺序排列的。

存储

ArrayList 中提供了多种添加元素的方法,下面将一一进行讲解:

1.set(int index, E element):该方法首先调用rangeCheck(index)来校验 index 变量是否超出数组范围,超出则抛出异常。而后,取出原 index 位置的值,并且将新的 element 放入 Index 位置,返回 oldValue。

  1. /**

  2.  

    * Replaces the element at the specified position in this list with

  3.  

    * the specified element.

  4.  

    *

  5.  

    * @param index index of the element to replace

  6.  

    * @param element element to be stored at the specified position

  7.  

    * @return the element previously at the specified position

  8.  

    * @throws IndexOutOfBoundsException {@inheritDoc}

  9.  

    */

  10.  

    public E set(int index, E element) {

  11.  

    rangeCheck(index);

  12.  

  13.  

    E oldValue = elementData(index);

  14.  

    elementData[index] = element;

  15.  

    return oldValue;

  16.  

    }

  17.  

    /**

  18.  

    * Checks if the given index is in range. If not, throws an appropriate

  19.  

    * runtime exception. This method does *not* check if the index is

  20.  

    * negative: It is always used immediately prior to an array access,

  21.  

    * which throws an ArrayIndexOutOfBoundsException if index is negative.

  22.  

    */

  23.  

    private void rangeCheck(int index) {

  24.  

    if (index >= size)

  25.  

    throw new IndexOutOfBoundsException(outOfBoundsMsg(index));

  26.  

    }

2.add(E e):该方法是将指定的元素添加到列表的尾部。当容量不足时,会调用 grow 方法增长容量。

  1. /**

  2.  

    * Appends the specified element to the end of this list.

  3.  

    *

  4.  

    * @param e element to be appended to this list

  5.  

    * @return <tt>true</tt> (as specified by {@link Collection#add})

  6.  

    */

  7.  

    public boolean add(E e) {

  8.  

    ensureCapacityInternal(size + 1); // Increments modCount!!

  9.  

    elementData[size++] = e;

  10.  

    return true;

  11.  

    }

  12.  

    private void ensureCapacityInternal(int minCapacity) {

  13.  

    modCount++;

  14.  

    // overflow-conscious code

  15.  

    if (minCapacity - elementData.length > 0)

  16.  

    grow(minCapacity);

  17.  

    }

  18.  

    private void grow(int minCapacity) {

  19.  

    // overflow-conscious code

  20.  

    int oldCapacity = elementData.length;

  21.  

    int newCapacity = oldCapacity + (oldCapacity >> 1);

  22.  

    if (newCapacity - minCapacity < 0)

  23.  

    newCapacity = minCapacity;

  24.  

    if (newCapacity - MAX_ARRAY_SIZE > 0)

  25.  

    newCapacity = hugeCapacity(minCapacity);

  26.  

    // minCapacity is usually close to size, so this is a win:

  27.  

    elementData = Arrays.copyOf(elementData, newCapacity);

  28.  

    }

3.add(int index, E element):在 index 位置插入 element。

  1. /**

  2.  

    * Inserts the specified element at the specified position in this

  3.  

    * list. Shifts the element currently at that position (if any) and

  4.  

    * any subsequent elements to the right (adds one to their indices).

  5.  

    *

  6.  

    * @param index index at which the specified element is to be inserted

  7.  

    * @param element element to be inserted

  8.  

    * @throws IndexOutOfBoundsException {@inheritDoc}

  9.  

    */

  10.  

    public void add(int index, E element) {

  11.  

    rangeCheckForAdd(index);

  12.  

  13.  

    ensureCapacityInternal(size + 1); // Increments modCount!!

  14.  

    System.arraycopy(elementData, index, elementData, index + 1,

  15.  

    size - index);

  16.  

    elementData[index] = element;

  17.  

    size++;

  18.  

    }

4.addAll(Collection<? extends E> c) 和 addAll(int index, Collection<? extends E> c):将特定 Collection 中的元素添加到 Arraylist 末尾。

  1. /**

  2.  

    * Appends all of the elements in the specified collection to the end of

  3.  

    * this list, in the order that they are returned by the

  4.  

    * specified collection‘s Iterator. The behavior of this operation is

  5.  

    * undefined if the specified collection is modified while the operation

  6.  

    * is in progress. (This implies that the behavior of this call is

  7.  

    * undefined if the specified collection is this list, and this

  8.  

    * list is nonempty.)

  9.  

    *

  10.  

    * @param c collection containing elements to be added to this list

  11.  

    * @return <tt>true</tt> if this list changed as a result of the call

  12.  

    * @throws NullPointerException if the specified collection is null

  13.  

    */

  14.  

    public boolean addAll(Collection<? extends E> c) {

  15.  

    Object[] a = c.toArray();

  16.  

    int numNew = a.length;

  17.  

    ensureCapacityInternal(size + numNew); // Increments modCount

  18.  

    System.arraycopy(a, 0, elementData, size, numNew);

  19.  

    size += numNew;

  20.  

    return numNew != 0;

  21.  

    }

  22.  

  23.  

    /**

  24.  

    * Inserts all of the elements in the specified collection into this

  25.  

    * list, starting at the specified position. Shifts the element

  26.  

    * currently at that position (if any) and any subsequent elements to

  27.  

    * the right (increases their indices). The new elements will appear

  28.  

    * in the list in the order that they are returned by the

  29.  

    * specified collection‘s iterator.

  30.  

    *

  31.  

    * @param index index at which to insert the first element from the

  32.  

    * specified collection

  33.  

    * @param c collection containing elements to be added to this list

  34.  

    * @return <tt>true</tt> if this list changed as a result of the call

  35.  

    * @throws IndexOutOfBoundsException {@inheritDoc}

  36.  

    * @throws NullPointerException if the specified collection is null

  37.  

    */

  38.  

    public boolean addAll(int index, Collection<? extends E> c) {

  39.  

    rangeCheckForAdd(index);

  40.  

  41.  

    Object[] a = c.toArray();

  42.  

    int numNew = a.length;

  43.  

    ensureCapacityInternal(size + numNew); // Increments modCount

  44.  

  45.  

    int numMoved = size - index;

  46.  

    if (numMoved > 0)

  47.  

    System.arraycopy(elementData, index, elementData, index + numNew,

  48.  

    numMoved);

  49.  

  50.  

    System.arraycopy(a, 0, elementData, index, numNew);

  51.  

    size += numNew;

  52.  

    return numNew != 0;

  53.  

    }

在 ArrayList 的存储方法,其核心本质是在数组的某个位置将元素添加进入。但其中又会涉及到关于数组容量不够而增长等因素。

读取

这个方法就比较简单了,ArrayList 能够支持随机访问的原因也是很显然的,因为它内部的数据结构是数组,而数组本身就是支持随机访问。该方法首先会判断输入的index值是否越界,然后将数组的 index 位置的元素返回即可。

  1. /**

  2.  

    * Returns the element at the specified position in this list.

  3.  

    *

  4.  

    * @param index index of the element to return

  5.  

    * @return the element at the specified position in this list

  6.  

    * @throws IndexOutOfBoundsException {@inheritDoc}

  7.  

    */

  8.  

    public E get(int index) {

  9.  

    rangeCheck(index);

  10.  

    return (E) elementData[index];

  11.  

    }

  12.  

    private void rangeCheck(int index) {

  13.  

    if (index >= size)

  14.  

    throw new IndexOutOfBoundsException(outOfBoundsMsg(index));

  15.  

    }

删除

ArrayList 提供了根据下标或者指定对象两种方式的删除功能。需要注意的是该方法的返回值并不相同,如下:

  1. /**

  2.  

    * Removes the element at the specified position in this list.

  3.  

    * Shifts any subsequent elements to the left (subtracts one from their

  4.  

    * indices).

  5.  

    *

  6.  

    * @param index the index of the element to be removed

  7.  

    * @return the element that was removed from the list

  8.  

    * @throws IndexOutOfBoundsException {@inheritDoc}

  9.  

    */

  10.  

    public E remove(int index) {

  11.  

    rangeCheck(index);

  12.  

  13.  

    modCount++;

  14.  

    E oldValue = elementData(index);

  15.  

  16.  

    int numMoved = size - index - 1;

  17.  

    if (numMoved > 0)

  18.  

    System.arraycopy(elementData, index+1, elementData, index,

  19.  

    numMoved);

  20.  

    elementData[--size] = null; // Let gc do its work

  21.  

  22.  

    return oldValue;

  23.  

    }

  24.  

    /**

  25.  

    * Removes the first occurrence of the specified element from this list,

  26.  

    * if it is present. If the list does not contain the element, it is

  27.  

    * unchanged. More formally, removes the element with the lowest index

  28.  

    * <tt>i</tt> such that

  29.  

    * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>

  30.  

    * (if such an element exists). Returns <tt>true</tt> if this list

  31.  

    * contained the specified element (or equivalently, if this list

  32.  

    * changed as a result of the call).

  33.  

    *

  34.  

    * @param o element to be removed from this list, if present

  35.  

    * @return <tt>true</tt> if this list contained the specified element

  36.  

    */

  37.  

    public boolean remove(Object o) {

  38.  

    if (o == null) {

  39.  

    for (int index = 0; index < size; index++)

  40.  

    if (elementData[index] == null) {

  41.  

    fastRemove(index);

  42.  

    return true;

  43.  

    }

  44.  

    } else {

  45.  

    for (int index = 0; index < size; index++)

  46.  

    if (o.equals(elementData[index])) {

  47.  

    fastRemove(index);

  48.  

    return true;

  49.  

    }

  50.  

    }

  51.  

    return false;

  52.  

    }

注意:从数组中移除元素的操作,也会导致被移除的元素以后的所有元素的向左移动一个位置。

调整数组容量

从上面介绍的向 ArrayList 中存储元素的代码中,我们看到,每当向数组中添加元素时,都要去检查添加后元素的个数是否会超出当前数组的长度,如果超出,数组将会进行扩容,以满足添加数据的需求。数组扩容有两个方法,其中开发者可以通过一个 public 的方法ensureCapacity(int minCapacity)来增加 ArrayList 的容量,而在存储元素等操作过程中,如果遇到容量不足,会调用priavte方法private void ensureCapacityInternal(int minCapacity)实现。

  1. public void ensureCapacity(int minCapacity) {

  2.  

    if (minCapacity > 0)

  3.  

    ensureCapacityInternal(minCapacity);

  4.  

    }

  5.  

  6.  

    private void ensureCapacityInternal(int minCapacity) {

  7.  

    modCount++;

  8.  

    // overflow-conscious code

  9.  

    if (minCapacity - elementData.length > 0)

  10.  

    grow(minCapacity);

  11.  

    }

  12.  

    /**

  13.  

    * Increases the capacity to ensure that it can hold at least the

  14.  

    * number of elements specified by the minimum capacity argument.

  15.  

    *

  16.  

    * @param minCapacity the desired minimum capacity

  17.  

    */

  18.  

    private void grow(int minCapacity) {

  19.  

    // overflow-conscious code

  20.  

    int oldCapacity = elementData.length;

  21.  

    int newCapacity = oldCapacity + (oldCapacity >> 1);

  22.  

    if (newCapacity - minCapacity < 0)

  23.  

    newCapacity = minCapacity;

  24.  

    if (newCapacity - MAX_ARRAY_SIZE > 0)

  25.  

    newCapacity = hugeCapacity(minCapacity);

  26.  

    // minCapacity is usually close to size, so this is a win:

  27.  

    elementData = Arrays.copyOf(elementData, newCapacity);

  28.  

    }

从上述代码中可以看出,数组进行扩容时,会将老数组中的元素重新拷贝一份到新的数组中,每次数组容量的增长大约是其原容量的 1.5 倍(从int newCapacity = oldCapacity + (oldCapacity >> 1)这行代码得出)。这种操作的代价是很高的,因此在实际使用时,我们应该尽量避免数组容量的扩张。当我们可预知要保存的元素的多少时,要在构造 ArrayList 实例时,就指定其容量,以避免数组扩容的发生。或者根据实际需求,通过调用ensureCapacity 方法来手动增加 ArrayList 实例的容量。

Fail-Fast 机制

ArrayList 也采用了快速失败的机制,通过记录 modCount 参数来实现。在面对并发的修改时,迭代器很快就会完全失败,而不是冒着在将来某个不确定时间发生任意不确定行为的风险。 关于 Fail-Fast 的更详细的介绍,我在之前将 HashMap 中已经提到。

LinkedList 的实现原理

概述

LinkedList 和 ArrayList 一样,都实现了 List 接口,但其内部的数据结构有本质的不同。LinkedList 是基于链表实现的(通过名字也能区分开来),所以它的插入和删除操作比 ArrayList 更加高效。但也是由于其为基于链表的,所以随机访问的效率要比 ArrayList 差。

看一下 LinkedList 的类的定义:

  1. public class LinkedList<E>

  2.  

    extends AbstractSequentialList<E>

  3.  

    implements List<E>, Deque<E>, Cloneable, java.io.Serializable

  4.  

    {}

LinkedList 继承自 AbstractSequenceList,实现了 List、Deque、Cloneable、java.io.Serializable 接口。AbstractSequenceList 提供了List接口骨干性的实现以减少实现 List 接口的复杂度,Deque 接口定义了双端队列的操作。

在 LinkedList 中除了本身自己的方法外,还提供了一些可以使其作为栈、队列或者双端队列的方法。这些方法可能彼此之间只是名字不同,以使得这些名字在特定的环境中显得更加合适。

LinkedList 也是 fail-fast 的(前边提过很多次了)。

LinkedList 源码解读

数据结构

LinkedList 是基于链表结构实现,所以在类中包含了 first 和 last 两个指针(Node)。Node 中包含了上一个节点和下一个节点的引用,这样就构成了双向的链表。每个 Node 只能知道自己的前一个节点和后一个节点,但对于链表来说,这已经足够了。

  1. transient int size = 0;

  2.  

    transient Node<E> first; //链表的头指针

  3.  

    transient Node<E> last; //尾指针

  4.  

    //存储对象的结构 Node, LinkedList的内部类

  5.  

    private static class Node<E> {

  6.  

    E item;

  7.  

    Node<E> next; // 指向下一个节点

  8.  

    Node<E> prev; //指向上一个节点

  9.  

  10.  

    Node(Node<E> prev, E element, Node<E> next) {

  11.  

    this.item = element;

  12.  

    this.next = next;

  13.  

    this.prev = prev;

  14.  

    }

  15.  

    }

存储

add(E e)

该方法是在链表的 end 添加元素,其调用了自己的方法 linkLast(E e)。

该方法首先将 last 的 Node 引用指向了一个新的 Node(l),然后根据l新建了一个 newNode,其中的元素就为要添加的 e;而后,我们让 last 指向了 newNode。接下来是自身进行维护该链表。

  1. /**

  2.  

    * Appends the specified element to the end of this list.

  3.  

    *

  4.  

    * <p>This method is equivalent to {@link #addLast}.

  5.  

    *

  6.  

    * @param e element to be appended to this list

  7.  

    * @return {@code true} (as specified by {@link Collection#add})

  8.  

    */

  9.  

    public boolean add(E e) {

  10.  

    linkLast(e);

  11.  

    return true;

  12.  

    }

  13.  

    /**

  14.  

    * Links e as last element.

  15.  

    */

  16.  

    void linkLast(E e) {

  17.  

    final Node<E> l = last;

  18.  

    final Node<E> newNode = new Node<>(l, e, null);

  19.  

    last = newNode;

  20.  

    if (l == null)

  21.  

    first = newNode;

  22.  

    else

  23.  

    l.next = newNode;

  24.  

    size++;

  25.  

    modCount++;

  26.  

    }

add(int index, E element)

该方法是在指定 index 位置插入元素。如果 index 位置正好等于 size,则调用 linkLast(element) 将其插入末尾;否则调用 linkBefore(element, node(index))方法进行插入。该方法的实现在下面,大家可以自己仔细的分析一下。(分析链表的时候最好能够边画图边分析)

  1. /**

  2.  

    * Inserts the specified element at the specified position in this list.

  3.  

    * Shifts the element currently at that position (if any) and any

  4.  

    * subsequent elements to the right (adds one to their indices).

  5.  

    *

  6.  

    * @param index index at which the specified element is to be inserted

  7.  

    * @param element element to be inserted

  8.  

    * @throws IndexOutOfBoundsException {@inheritDoc}

  9.  

    */

  10.  

    public void add(int index, E element) {

  11.  

    checkPositionIndex(index);

  12.  

  13.  

    if (index == size)

  14.  

    linkLast(element);

  15.  

    else

  16.  

    linkBefore(element, node(index));

  17.  

    }

  18.  

    /**

  19.  

    * Inserts element e before non-null Node succ.

  20.  

    */

  21.  

    void linkBefore(E e, Node<E> succ) {

  22.  

    // assert succ != null;

  23.  

    final Node<E> pred = succ.prev;

  24.  

    final Node<E> newNode = new Node<>(pred, e, succ);

  25.  

    succ.prev = newNode;

  26.  

    if (pred == null)

  27.  

    first = newNode;

  28.  

    else

  29.  

    pred.next = newNode;

  30.  

    size++;

  31.  

    modCount++;

  32.  

    }

LinkedList 的方法实在是太多,在这没法一一举例分析。但很多方法其实都只是在调用别的方法而已,所以建议大家将其几个最核心的添加的方法搞懂就可以了,比如 linkBefore、linkLast。其本质也就是链表之间的删除添加等。

ConcurrentHashMap 的实现原理

概述

我们在之前的博文中了解到关于 HashMap 和 Hashtable 这两种集合。其中 HashMap 是非线程安全的,当我们只有一个线程在使用 HashMap 的时候,自然不会有问题,但如果涉及到多个线程,并且有读有写的过程中,HashMap 就不能满足我们的需要了(fail-fast)。在不考虑性能问题的时候,我们的解决方案有 Hashtable 或者Collections.synchronizedMap(hashMap),这两种方式基本都是对整个 hash 表结构做锁定操作的,这样在锁表的期间,别的线程就需要等待了,无疑性能不高。

所以我们在本文中学习一个 util.concurrent 包的重要成员,ConcurrentHashMap。

ConcurrentHashMap 的实现是依赖于 Java 内存模型,所以我们在了解 ConcurrentHashMap 的前提是必须了解Java 内存模型。但 Java 内存模型并不是本文的重点,所以我假设读者已经对 Java 内存模型有所了解。

ConcurrentHashMap 分析

ConcurrentHashMap 的结构是比较复杂的,都深究去本质,其实也就是数组和链表而已。我们由浅入深慢慢的分析其结构。

先简单分析一下,ConcurrentHashMap 的成员变量中,包含了一个 Segment 的数组(final Segment<K,V>[] segments;),而 Segment 是 ConcurrentHashMap 的内部类,然后在 Segment 这个类中,包含了一个 HashEntry 的数组(transient volatile HashEntry<K,V>[] table;)。而 HashEntry 也是 ConcurrentHashMap 的内部类。HashEntry 中,包含了 key 和 value 以及 next 指针(类似于 HashMap 中 Entry),所以 HashEntry 可以构成一个链表。

所以通俗的讲,ConcurrentHashMap 数据结构为一个 Segment 数组,Segment 的数据结构为 HashEntry 的数组,而 HashEntry 存的是我们的键值对,可以构成链表。

首先,我们看一下 HashEntry 类。

HashEntry

HashEntry 用来封装散列映射表中的键值对。在 HashEntry 类中,key,hash 和 next 域都被声明为 final 型,value 域被声明为 volatile 型。其类的定义为:

  1. static final class HashEntry<K,V> {

  2.  

    final int hash;

  3.  

    final K key;

  4.  

    volatile V value;

  5.  

    volatile HashEntry<K,V> next;

  6.  

  7.  

    HashEntry(int hash, K key, V value, HashEntry<K,V> next) {

  8.  

    this.hash = hash;

  9.  

    this.key = key;

  10.  

    this.value = value;

  11.  

    this.next = next;

  12.  

    }

  13.  

    ...

  14.  

    ...

  15.  

    }

HashEntry 的学习可以类比着 HashMap 中的 Entry。我们的存储键值对的过程中,散列的时候如果发生“碰撞”,将采用“分离链表法”来处理碰撞:把碰撞的 HashEntry 对象链接成一个链表。

如下图,我们在一个空桶中插入 A、B、C 两个 HashEntry 对象后的结构图(其实应该为键值对,在这进行了简化以方便更容易理解):

Segment

Segment 的类定义为static final class Segment<K,V> extends ReentrantLock implements Serializable。其继承于 ReentrantLock 类,从而使得 Segment 对象可以充当锁的角色。Segment 中包含HashEntry 的数组,其可以守护其包含的若干个桶(HashEntry的数组)。Segment 在某些意义上有点类似于 HashMap了,都是包含了一个数组,而数组中的元素可以是一个链表。

table:table 是由 HashEntry 对象组成的数组如果散列时发生碰撞,碰撞的 HashEntry 对象就以链表的形式链接成一个链表table数组的数组成员代表散列映射表的一个桶每个 table 守护整个 ConcurrentHashMap 包含桶总数的一部分如果并发级别为 16,table 则守护 ConcurrentHashMap 包含的桶总数的 1/16。

count 变量是计算器,表示每个 Segment 对象管理的 table 数组(若干个 HashEntry 的链表)包含的HashEntry 对象的个数。之所以在每个Segment对象中包含一个 count 计数器,而不在 ConcurrentHashMap 中使用全局的计数器,是为了避免出现“热点域”而影响并发性。

  1. /**

  2.  

    * Segments are specialized versions of hash tables. This

  3.  

    * subclasses from ReentrantLock opportunistically, just to

  4.  

    * simplify some locking and avoid separate construction.

  5.  

    */

  6.  

    static final class Segment<K,V> extends ReentrantLock implements Serializable {

  7.  

    /**

  8.  

    * The per-segment table. Elements are accessed via

  9.  

    * entryAt/setEntryAt providing volatile semantics.

  10.  

    */

  11.  

    transient volatile HashEntry<K,V>[] table;

  12.  

  13.  

    /**

  14.  

    * The number of elements. Accessed only either within locks

  15.  

    * or among other volatile reads that maintain visibility.

  16.  

    */

  17.  

    transient int count;

  18.  

    transient int modCount;

  19.  

    /**

  20.  

    * 装载因子

  21.  

    */

  22.  

    final float loadFactor;

  23.  

    }

我们通过下图来展示一下插入 ABC 三个节点后,Segment 的示意图:

其实从我个人角度来说,Segment结构是与HashMap很像的。

ConcurrentHashMap

ConcurrentHashMap 的结构中包含的 Segment 的数组,在默认的并发级别会创建包含 16 个 Segment 对象的数组。通过我们上面的知识,我们知道每个 Segment 又包含若干个散列表的桶,每个桶是由 HashEntry 链接起来的一个链表。如果 key 能够均匀散列,每个 Segment 大约守护整个散列表桶总数的 1/16。

下面我们还有通过一个图来演示一下 ConcurrentHashMap 的结构:

并发写操作

在 ConcurrentHashMap 中,当执行 put 方法的时候,会需要加锁来完成。我们通过代码来解释一下具体过程: 当我们 new 一个 ConcurrentHashMap 对象,并且执行put操作的时候,首先会执行 ConcurrentHashMap 类中的 put 方法,该方法源码为:

  1. /**

  2.  

    * Maps the specified key to the specified value in this table.

  3.  

    * Neither the key nor the value can be null.

  4.  

    *

  5.  

    * <p> The value can be retrieved by calling the <tt>get</tt> method

  6.  

    * with a key that is equal to the original key.

  7.  

    *

  8.  

    * @param key key with which the specified value is to be associated

  9.  

    * @param value value to be associated with the specified key

  10.  

    * @return the previous value associated with <tt>key</tt>, or

  11.  

    * <tt>null</tt> if there was no mapping for <tt>key</tt>

  12.  

    * @throws NullPointerException if the specified key or value is null

  13.  

    */

  14.  

    @SuppressWarnings("unchecked")

  15.  

    public V put(K key, V value) {

  16.  

    Segment<K,V> s;

  17.  

    if (value == null)

  18.  

    throw new NullPointerException();

  19.  

    int hash = hash(key);

  20.  

    int j = (hash >>> segmentShift) & segmentMask;

  21.  

    if ((s = (Segment<K,V>)UNSAFE.getObject // nonvolatile; recheck

  22.  

    (segments, (j << SSHIFT) + SBASE)) == null) // in ensureSegment

  23.  

    s = ensureSegment(j);

  24.  

    return s.put(key, hash, value, false);

  25.  

    }

我们通过注释可以了解到,ConcurrentHashMap 不允许空值。该方法首先有一个 Segment 的引用 s,然后会通过 hash() 方法对 key 进行计算,得到哈希值;继而通过调用 Segment 的 put(K key, int hash, V value, boolean onlyIfAbsent)方法进行存储操作。该方法源码为:

  1. final V put(K key, int hash, V value, boolean onlyIfAbsent) {

  2.  

    //加锁,这里是锁定的Segment而不是整个ConcurrentHashMap

  3.  

    HashEntry<K,V> node = tryLock() ? null :scanAndLockForPut(key, hash, value);

  4.  

    V oldValue;

  5.  

    try {

  6.  

    HashEntry<K,V>[] tab = table;

  7.  

    //得到hash对应的table中的索引index

  8.  

    int index = (tab.length - 1) & hash;

  9.  

    //找到hash对应的是具体的哪个桶,也就是哪个HashEntry链表

  10.  

    HashEntry<K,V> first = entryAt(tab, index);

  11.  

    for (HashEntry<K,V> e = first;;) {

  12.  

    if (e != null) {

  13.  

    K k;

  14.  

    if ((k = e.key) == key ||

  15.  

    (e.hash == hash && key.equals(k))) {

  16.  

    oldValue = e.value;

  17.  

    if (!onlyIfAbsent) {

  18.  

    e.value = value;

  19.  

    ++modCount;

  20.  

    }

  21.  

    break;

  22.  

    }

  23.  

    e = e.next;

  24.  

    }

  25.  

    else {

  26.  

    if (node != null)

  27.  

    node.setNext(first);

  28.  

    else

  29.  

    node = new HashEntry<K,V>(hash, key, value, first);

  30.  

    int c = count + 1;

  31.  

    if (c > threshold && tab.length < MAXIMUM_CAPACITY)

  32.  

    rehash(node);

  33.  

    else

  34.  

    setEntryAt(tab, index, node);

  35.  

    ++modCount;

  36.  

    count = c;

  37.  

    oldValue = null;

  38.  

    break;

  39.  

    }

  40.  

    }

  41.  

    } finally {

  42.  

    //解锁

  43.  

    unlock();

  44.  

    }

  45.  

    return oldValue;

  46.  

    }

关于该方法的某些关键步骤,在源码上加上了注释。

需要注意的是:加锁操作是针对的 hash 值对应的某个 Segment,而不是整个 ConcurrentHashMap。因为 put 操作只是在这个 Segment 中完成,所以并不需要对整个 ConcurrentHashMap 加锁。所以,此时,其他的线程也可以对另外的 Segment 进行 put 操作,因为虽然该 Segment 被锁住了,但其他的 Segment 并没有加锁。同时,读线程并不会因为本线程的加锁而阻塞。

正是因为其内部的结构以及机制,所以 ConcurrentHashMap 在并发访问的性能上要比Hashtable和同步包装之后的HashMap的性能提高很多。在理想状态下,ConcurrentHashMap 可以支持 16 个线程执行并发写操作(如果并发级别设置为 16),及任意数量线程的读操作。

总结

在实际的应用中,散列表一般的应用场景是:除了少数插入操作和删除操作外,绝大多数都是读取操作,而且读操作在大多数时候都是成功的。正是基于这个前提,ConcurrentHashMap 针对读操作做了大量的优化。通过 HashEntry 对象的不变性和用 volatile 型变量协调线程间的内存可见性,使得 大多数时候,读操作不需要加锁就可以正确获得值。这个特性使得 ConcurrentHashMap 的并发性能在分离锁的基础上又有了近一步的提高。

ConcurrentHashMap 是一个并发散列映射表的实现,它允许完全并发的读取,并且支持给定数量的并发更新。相比于 HashTable 和用同步包装器包装的 HashMap(Collections.synchronizedMap(new HashMap())),ConcurrentHashMap 拥有更高的并发性。在 HashTable 和由同步包装器包装的 HashMap 中,使用一个全局的锁来同步不同线程间的并发访问。同一时间点,只能有一个线程持有锁,也就是说在同一时间点,只能有一个线程能访问容器。这虽然保证多线程间的安全并发访问,但同时也导致对容器的访问变成串行化的了。

ConcurrentHashMap 的高并发性主要来自于三个方面:

  • 用分离锁实现多个线程间的更深层次的共享访问。
  • 用 HashEntery 对象的不变性来降低执行读操作的线程在遍历链表期间对加锁的需求。
  • 通过对同一个 Volatile 变量的写 / 读访问,协调不同线程间读 / 写操作的内存可见性。

使用分离锁,减小了请求 同一个锁的频率。

通过 HashEntery 对象的不变性及对同一个 Volatile 变量的读 / 写来协调内存可见性,使得 读操作大多数时候不需要加锁就能成功获取到需要的值。由于散列映射表在实际应用中大多数操作都是成功的 读操作,所以 2 和 3 既可以减少请求同一个锁的频率,也可以有效减少持有锁的时间。通过减小请求同一个锁的频率和尽量减少持有锁的时间 ,使得 ConcurrentHashMap 的并发性相对于 HashTable 和用同步包装器包装的 HashMap有了质的提高。

LinkedHashMap 与 LRUcache

LRU 缓存介绍

我们平时总会有一个电话本记录所有朋友的电话,但是,如果有朋友经常联系,那些朋友的电话号码不用翻电话本我们也能记住,但是,如果长时间没有联系了,要再次联系那位朋友的时候,我们又不得不求助电话本,但是,通过电话本查找还是很费时间的。但是,我们大脑能够记住的东西是一定的,我们只能记住自己最熟悉的,而长时间不熟悉的自然就忘记了。

其实,计算机也用到了同样的一个概念,我们用缓存来存放以前读取的数据,而不是直接丢掉,这样,再次读取的时候,可以直接在缓存里面取,而不用再重新查找一遍,这样系统的反应能力会有很大提高。但是,当我们读取的个数特别大的时候,我们不可能把所有已经读取的数据都放在缓存里,毕竟内存大小是一定的,我们一般把最近常读取的放在缓存里(相当于我们把最近联系的朋友的姓名和电话放在大脑里一样)。

LRU 缓存利用了这样的一种思想。LRU 是 Least Recently Used 的缩写,翻译过来就是“最近最少使用”,也就是说,LRU 缓存把最近最少使用的数据移除,让给最新读取的数据。而往往最常读取的,也是读取次数最多的,所以,利用 LRU 缓存,我们能够提高系统的 performance。

实现

要实现 LRU 缓存,我们首先要用到一个类 LinkedHashMap。

用这个类有两大好处:一是它本身已经实现了按照访问顺序的存储,也就是说,最近读取的会放在最前面,最最不常读取的会放在最后(当然,它也可以实现按照插入顺序存储)。第二,LinkedHashMap 本身有一个方法用于判断是否需要移除最不常读取的数,但是,原始方法默认不需要移除(这是,LinkedHashMap 相当于一个linkedlist),所以,我们需要 override 这样一个方法,使得当缓存里存放的数据个数超过规定个数后,就把最不常用的移除掉。关于 LinkedHashMap 中已经有详细的介绍。

代码如下:(可直接复制,也可以通过LRUcache-Java下载)

  1. import java.util.LinkedHashMap;

  2.  

    import java.util.Collection;

  3.  

    import java.util.Map;

  4.  

    import java.util.ArrayList;

  5.  

  6.  

    /**

  7.  

    * An LRU cache, based on <code>LinkedHashMap</code>.

  8.  

    *

  9.  

    * <p>

  10.  

    * This cache has a fixed maximum number of elements (<code>cacheSize</code>).

  11.  

    * If the cache is full and another entry is added, the LRU (least recently

  12.  

    * used) entry is dropped.

  13.  

    *

  14.  

    * <p>

  15.  

    * This class is thread-safe. All methods of this class are synchronized.

  16.  

    *

  17.  

    * <p>

  18.  

    * Author: Christian d‘Heureuse, Inventec Informatik AG, Zurich, Switzerland<br>

  19.  

    * Multi-licensed: EPL / LGPL / GPL / AL / BSD.

  20.  

    */

  21.  

    public class LRUCache<K, V> {

  22.  

    private static final float hashTableLoadFactor = 0.75f;

  23.  

    private LinkedHashMap<K, V> map;

  24.  

    private int cacheSize;

  25.  

  26.  

    /**

  27.  

    * Creates a new LRU cache. 在该方法中,new LinkedHashMap<K,V>(hashTableCapacity,

  28.  

    * hashTableLoadFactor, true)中,true代表使用访问顺序

  29.  

    *

  30.  

    * @param cacheSize

  31.  

    * the maximum number of entries that will be kept in this cache.

  32.  

    */

  33.  

    public LRUCache(int cacheSize) {

  34.  

    this.cacheSize = cacheSize;

  35.  

    int hashTableCapacity = (int) Math

  36.  

    .ceil(cacheSize / hashTableLoadFactor) + 1;

  37.  

    map = new LinkedHashMap<K, V>(hashTableCapacity, hashTableLoadFactor,

  38.  

    true) {

  39.  

    // (an anonymous inner class)

  40.  

    private static final long serialVersionUID = 1;

  41.  

  42.  

    @Override

  43.  

    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {

  44.  

    return size() > LRUCache.this.cacheSize;

  45.  

    }

  46.  

    };

  47.  

    }

  48.  

  49.  

    /**

  50.  

    * Retrieves an entry from the cache.<br>

  51.  

    * The retrieved entry becomes the MRU (most recently used) entry.

  52.  

    *

  53.  

    * @param key

  54.  

    * the key whose associated value is to be returned.

  55.  

    * @return the value associated to this key, or null if no value with this

  56.  

    * key exists in the cache.

  57.  

    */

  58.  

    public synchronized V get(K key) {

  59.  

    return map.get(key);

  60.  

    }

  61.  

  62.  

    /**

  63.  

    * Adds an entry to this cache. The new entry becomes the MRU (most recently

  64.  

    * used) entry. If an entry with the specified key already exists in the

  65.  

    * cache, it is replaced by the new entry. If the cache is full, the LRU

  66.  

    * (least recently used) entry is removed from the cache.

  67.  

    *

  68.  

    * @param key

  69.  

    * the key with which the specified value is to be associated.

  70.  

    * @param value

  71.  

    * a value to be associated with the specified key.

  72.  

    */

  73.  

    public synchronized void put(K key, V value) {

  74.  

    map.put(key, value);

  75.  

    }

  76.  

  77.  

    /**

  78.  

    * Clears the cache.

  79.  

    */

  80.  

    public synchronized void clear() {

  81.  

    map.clear();

  82.  

    }

  83.  

  84.  

    /**

  85.  

    * Returns the number of used entries in the cache.

  86.  

    *

  87.  

    * @return the number of entries currently in the cache.

  88.  

    */

  89.  

    public synchronized int usedEntries() {

  90.  

    return map.size();

  91.  

    }

  92.  

  93.  

    /**

  94.  

    * Returns a <code>Collection</code> that contains a copy of all cache

  95.  

    * entries.

  96.  

    *

  97.  

    * @return a <code>Collection</code> with a copy of the cache content.

  98.  

    */

  99.  

    public synchronized Collection<Map.Entry<K, V>> getAll() {

  100.  

    return new ArrayList<Map.Entry<K, V>>(map.entrySet());

  101.  

    }

  102.  

  103.  

    // Test routine for the LRUCache class.

  104.  

    public static void main(String[] args) {

  105.  

    LRUCache<String, String> c = new LRUCache<String, String>(3);

  106.  

    c.put("1", "one"); // 1

  107.  

    c.put("2", "two"); // 2 1

  108.  

    c.put("3", "three"); // 3 2 1

  109.  

    c.put("4", "four"); // 4 3 2

  110.  

    if (c.get("2") == null)

  111.  

    throw new Error(); // 2 4 3

  112.  

    c.put("5", "five"); // 5 2 4

  113.  

    c.put("4", "second four"); // 4 5 2

  114.  

    // Verify cache content.

  115.  

    if (c.usedEntries() != 3)

  116.  

    throw new Error();

  117.  

    if (!c.get("4").equals("second four"))

  118.  

    throw new Error();

  119.  

    if (!c.get("5").equals("five"))

  120.  

    throw new Error();

  121.  

    if (!c.get("2").equals("two"))

  122.  

    throw new Error();

  123.  

    // List cache content.

  124.  

    for (Map.Entry<String, String> e : c.getAll())

  125.  

    System.out.println(e.getKey() + " : " + e.getValue());

  126.  

    }

  127.  

    }


HashSet 和 HashMap 的比较

HashMap 和 HashSet 都是 collection 框架的一部分,它们让我们能够使用对象的集合。collection 框架有自己的接口和实现,主要分为 Set 接口,List 接口和 Queue 接口。它们有各自的特点,Set 的集合里不允许对象有重复的值,List 允许有重复,它对集合中的对象进行索引,Queue 的工作原理是 FCFS 算法(First Come, First Serve)。

首先让我们来看看什么是 HashMap 和 HashSet,然后再来比较它们之间的分别。

什么是 HashSet

HashSet 实现了 Set 接口,它不允许集合中有重复的值,当我们提到 HashSet 时,第一件事情就是在将对象存储在 HashSet 之前,要先确保对象重写 equals()和 hashCode()方法,这样才能比较对象的值是否相等,以确保set中没有储存相等的对象。如果我们没有重写这两个方法,将会使用这个方法的默认实现。

public boolean add(Object o)方法用来在 Set 中添加元素,当元素值重复时则会立即返回 false,如果成功添加的话会返回 true。

什么是 HashMap

HashMap 实现了 Map 接口,Map 接口对键值对进行映射。Map 中不允许重复的键。Map 接口有两个基本的实现,HashMap 和 TreeMap。TreeMap 保存了对象的排列次序,而 HashMap 则不能。HashMap 允许键和值为 null。HashMap 是非 synchronized 的,但 collection 框架提供方法能保证 HashMap synchronized,这样多个线程同时访问 HashMap 时,能保证只有一个线程更改 Map。

public Object put(Object Key,Object value)方法用来将元素添加到 map 中。

HashSet 和 HashMap 的区别

HashMap HashSet
HashMap实现了Map接口 HashSet实现了Set接口
HashMap储存键值对 HashSet仅仅存储对象
使用put()方法将元素放入map中 使用add()方法将元素放入set中
HashMap中使用键对象来计算hashcode值 HashSet使用成员对象来计算hashcode值,对于两个对象来说hashcode可能相同,所以equals()方法用来判断对象的相等性,如果两个对象不同的话,那么返回false
HashMap比较快,因为是使用唯一的键来获取对象 HashSet较HashMap来说比较慢

ct o)方法用来在 Set 中添加元素,当元素值重复时则会立即返回 false,如果成功添加的话会返回 true。

什么是 HashMap

HashMap 实现了 Map 接口,Map 接口对键值对进行映射。Map 中不允许重复的键。Map 接口有两个基本的实现,HashMap 和 TreeMap。TreeMap 保存了对象的排列次序,而 HashMap 则不能。HashMap 允许键和值为 null。HashMap 是非 synchronized 的,但 collection 框架提供方法能保证 HashMap synchronized,这样多个线程同时访问 HashMap 时,能保证只有一个线程更改 Map。

public Object put(Object Key,Object value)方法用来将元素添加到 map 中。

HashSet 和 HashMap 的区别

HashMap HashSet
HashMap实现了Map接口 HashSet实现了Set接口
HashMap储存键值对 HashSet仅仅存储对象
使用put()方法将元素放入map中 使用add()方法将元素放入set中
HashMap中使用键对象来计算hashcode值 HashSet使用成员对象来计算hashcode值,对于两个对象来说hashcode可能相同,所以equals()方法用来判断对象的相等性,如果两个对象不同的话,那么返回false
HashMap比较快,因为是使用唯一的键来获取对象 HashSet较HashMap来说比较慢

原文地址:https://www.cnblogs.com/lixiang6839/p/9378357.html

时间: 2024-07-28 16:05:04

java map的实现原理的相关文章

java map按照value值来比较大小并且返回最终结果

代码下载地址:http://www.zuidaima.com/share/1830834176347136.htm 原文:java map按照value值来比较大小并且返回最终结果 package com.zuidaima.util; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; public class ValueComparator

Java Map 如何实现Key 的唯一性?

大家都知道,在Map和Set不可存在重复元素? 但是对于内部的细节我们并不了解,今天我们就一块来 探讨一下! 1 对于 HashMap  HashSet 他们的底层数据结构的实现是:维护了一张  HashTable .容器中的元素全部存储在Hashtable 中.他们再添加元素的时候,是如何判断是否存在有重复元素的呢?  每一个被添加的元素都有一个 hashCode(哈希值),他们先比较哈希值,是否相同? 不相同的元素,添加进入 HashTable.   如果hashCode相同的话, 再去比较

【Java】Servlet 工作原理解析

Web 技术成为当今主流的互联网 Web 应用技术之一,而 Servlet 是 Java Web 技术的核心基础.因而掌握 Servlet 的工作原理是成为一名合格的 Java Web 技术开发人员的基本要求.本文将带你认识 Java Web 技术是如何基于 Servlet 工作,你将知道:以 Tomcat 为例了解 Servlet 容器是如何工作的?一个 Web 工程在 Servlet 容器中是如何启动的? Servlet 容器如何解析你在 web.xml 中定义的 Servlet ?用户的请

java多线程模式ThreadLocal原理简述及其使用详解

原创整理不易,转载请注明出处:java多线程模式ThreadLocal原理简述及其使用详解 代码下载地址:http://www.zuidaima.com/share/1781557457128448.htm ThreadLocal是为了使每个线程保存一份属于自己的数据. 先看一个使用ThreadLocal的实例. package com.zuidaima.aop.framework; import com.zuidaima.core.NamedThreadLocal; public abstra

[Java] 监控java对象回收的原理与实现

监控Java对象回收的原理与实现 一.监控Java对象回收的目的 监控Java对象是否回收的目的是:为了实现内存泄露报警. 内存泄露是指程序中对象生命周期(点击查看详情)已经进入不可见阶段,但由于编码错误或系统原因,仍然存在着GC roots持有或间接持有该对象的引用,导致该对象的生命周期无法继续向下流转,也就无法释放的现象.简单的来说即是:已实例化的对象长期被持有且无法释放或不能按照对象正常的生命周期进行释放.(点击这里查看<[Android]内存泄露排查实战手记>) 实现内存泄露报警,可以

java Map排序(升序、降序、随机排序)

基础知识: 1 HashMap会使用key,根据hashcode进行默认排序. 2  LinkedHashMap根据存入先后进行排序 代码展示: 1 随机排序 java Map排序(升序.降序.随机排序),布布扣,bubuko.com

Java Map遍历方式的选择

1. 阐述 对于Java中Map的遍历方式,很多文章都推荐使用entrySet,认为其比keySet的效率高很多.理由是:entrySet方法一次拿到所有key和value的集合:而keySet拿到的只是key的集合,针对每个key,都要去Map中额外查找一次value,从而降低了总体效率.那么实际情况如何呢? 为了解遍历性能的真实差距,包括在遍历key+value.遍历key.遍历value等不同场景下的差异,我试着进行了一些对比测试. 2. 对比测试 一开始只进行了简单的测试,但结果却表明k

Java类加载器工作原理

Java类加载器是用来在运行时加载类(*.class文件).Java类加载器基于三个原则:委托.可见性.唯一性.委托原则把加载类的请求转发给父 类加载器,而且仅加载类当父 类加载器无法找到或者不能加载类时.可见性原则允许子类加载器查看由父类加载器加载的所有的类,但是父类加载器不能查看由子类加载器加载的类.唯一性原则只允许加载一次类文件,这基本上是通过委托原则来实现的并确保子类加载器不重新加载由父类加载器加载过的类.正确的理解类加载器原理必须解决像 NoClassDefFoundError in

Java 线程池的原理与实现

最近在学习线程池.内存控制等关于提高程序运行性能方面的编程技术,在网上看到有一哥们写得不错,故和大家一起分享. [分享]Java 线程池的原理与实现 这几天主要是狂看源程序,在弥补了一些以前知识空白的同时,也学会了不少新的知识(比如 NIO),或者称为新技术吧.线程池就是其中之一,一提到线程,我们会想到以前<操作系统>的生产者与消费者,信号量,同步控制等等.一提到池,我们会想到数据库连接池,但是线程池又如何呢? 建议:在阅读本文前,先理一理同步的知识,特别是syncronized同步关键字的用