HashSet与LinkedHashSet

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (14)

他们之间有什么区别?我知道

LinkedHashSet是HashSet的一个有序版本,它在所有元素中维护一个双链接列表。当关心迭代顺序时,使用这个类而不是HashSet。当迭代HashSet时,顺序是不可预测的,而LinkedHashSet允许按照插入元素的顺序迭代元素。

但是在LinkedHashSet的源代码中,只有对HashSet的构造函数进行调用。那么,双链接列表和插入顺序在哪里呢?

提问于
用户回答回答于

LinkedHashSet用于构造基类:

public LinkedHashSet(int initialCapacity, float loadFactor) {
    super(initialCapacity, loadFactor, true);      // <-- boolean dummy argument
}

...

public LinkedHashSet(int initialCapacity) {
    super(initialCapacity, .75f, true);            // <-- boolean dummy argument
}

...

public LinkedHashSet() {
    super(16, .75f, true);                         // <-- boolean dummy argument
}

...

public LinkedHashSet(Collection<? extends E> c) {
    super(Math.max(2*c.size(), 11), .75f, true);   // <-- boolean dummy argument
    addAll(c);
}

aHashSet使用布尔参数的构造函数将被描述,如下所示:

/**
 * 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<E,Object>(initialCapacity, loadFactor);
}
用户回答回答于

LinkedHashSet其构造函数调用以下基类构造函数:

HashSet(int initialCapacity, float loadFactor, boolean dummy) {
  map = new LinkedHashMap<E, Object>(initialCapacity, loadFactor);
}

如你所见,内部地图是LinkedHashMap,如果你看里面LinkedHashMap,将发现以下字段:

private transient Entry<K, V> header;

扫码关注云+社区