源码阅读 - LinkedHashSet

本文中关于LinkedHashMap的部分参考源码阅读 - LinkedHashMap

0. LinkedHashSet是什么

  • LinkedHashSet继承自HashSet
  • 通过LinkedHashMap实现

1. 实现原理

LinkedHashSet的构造函数中均调用了

super(initialCapacity, loadFactor, true);

HashSet中的构造方法:

/**
 * Constructs a new, empty linked hash set.  (This package private
 * constructor is only used by LinkedHashSet.) The backing
 * HashMap instance is a LinkedHashMap with the specified initial
 * capacity and the specified load factor.
 *
 * @param      initialCapacity   the initial capacity of the hash map
 * @param      loadFactor        the load factor of the hash map
 * @param      dummy             ignored (distinguishes this
 *             constructor from other int, float constructor.)
 * @throws     IllegalArgumentException if the initial capacity is less
 *             than zero, or if the load factor is nonpositive
 */
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
    map = new LinkedHashMap<>(initialCapacity, loadFactor);
}

所以LinkedHashSet可以按照插入顺序来遍历,但是不能按照访问顺序遍历。

你可能感兴趣的:(源码阅读 - LinkedHashSet)