一、概述
LinkedHashSet 实现了 Set 接口,同时 LinkedHashSet 迭代是有序的。
LinkedHashSet 继承自 HashSet
1、通过 HashSet 实现 Set 的元素唯一性。
2、在 HashSet 中存在私有构造,通过 LinkedHashMap 来实现集合迭代的有序性 《HashSet 私有构造》
二、代码分析
LinkedHashSet 继承于 HashSet ,有基于 LinkedHashMap 《LinkedHashMap》实现。
通过 LinkedHashMap 来保存所有元素,同时使用 LinkedHashMap 中维护的链表来保证迭代的有序性。
通过 HashSet 来保证元素的唯一性。
2.1、构造函数
/**
* Constructs a new, empty linked hash set with the specified initial
* capacity and load factor.
*
* @param initialCapacity the initial capacity of the linked hash set
* @param loadFactor the load factor of the linked hash set
* @throws IllegalArgumentException if the initial capacity is less
* than zero, or if the load factor is nonpositive
*/
public LinkedHashSet(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor, true);
}
/**
* Constructs a new, empty linked hash set with the specified initial
* capacity and the default load factor (0.75).
*
* @param initialCapacity the initial capacity of the LinkedHashSet
* @throws IllegalArgumentException if the initial capacity is less
* than zero
*/
public LinkedHashSet(int initialCapacity) {
super(initialCapacity, .75f, true);
}
/**
* Constructs a new, empty linked hash set with the default initial
* capacity (16) and load factor (0.75).
*/
public LinkedHashSet() {
super(16, .75f, true);
}
/**
* Constructs a new linked hash set with the same elements as the
* specified collection. The linked hash set is created with an initial
* capacity sufficient to hold the elements in the specified collection
* and the default load factor (0.75).
*
* @param c the collection whose elements are to be placed into
* this set
* @throws NullPointerException if the specified collection is null
*/
public LinkedHashSet(Collection<? extends E> c) {
super(Math.max(2*c.size(), 11), .75f, true);
addAll(c);
}
上述所有的构造函数最终调用的都是 HashSet 中的私有构造,如下