正如您所说,两者之间的区别是:
A LinkedHashSet
是一个有序版本HashSet
它维护一个跨所有元素的双向链接列表。使用此类代替HashSet
当您关心迭代顺序时。当你迭代一个HashSet
顺序是不可预测的,而LinkedHashSet
允许您按照插入顺序遍历元素。
至于你的问题:
但LinkedHashSet的源代码中只有调用HashSet的构造函数。
答案在于哪些构造函数 the 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);
}