问题

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

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

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


#1 热门回答(55 赞)

答案在于**,其中构造函数**和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);
}

#2 热门回答(23 赞)

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

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

如你所见,内部 Map 是aLinkedHashMap。如果你查看LinkedHashMap,你将发现以下字段:

private transient Entry<K, V> header;

这是有问题的链表。


#3 热门回答(9 赞)

你应该看看它调用的HashSet构造函数的来源......它是一个特殊的构造函数,它使backMapaLinkedHashMap不仅仅是aHashMap


原文链接