它们之间的区别是什么?我知道
A LinkedHashSet是HashSet的有序版本,它跨所有元素维护一个双向链表。当您关心迭代顺序时,请使用此类而不是HashSet。当您遍历HashSet时,顺序是不可预测的,而LinkedHashSet允许您按照元素插入的顺序遍历元素。
但在LinkedHashSet源码中,只有HashSet的调用构造函数。那么,双向链表和插入顺序在哪里呢?
发布于 2011-02-23 00:10:47
答案就在中,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);
}
下面描述了一个接受布尔参数的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<E,Object>(initialCapacity, loadFactor);
}
发布于 2016-07-01 17:33:23
HashSet是无序和无序的集合。
LinkedHashSet是HashSet的订购版本。
HashSet和LinkedHashSet之间的唯一区别是:
LinkedHashSet会维护插入顺序。
当我们遍历HashSet时,顺序是不可预测的,而对于LinkedHashSet.,顺序是可预测的
LinkedHashSet保持插入顺序的原因是:
底层使用的数据结构是Doubly-Linked-List.
发布于 2011-02-23 00:11:49
LinkedHashSet
的构造函数调用以下基类构造函数:
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<E, Object>(initialCapacity, loadFactor);
}
如您所见,内部映射是一个LinkedHashMap
。如果您查看LinkedHashMap
内部,您将发现以下字段:
private transient Entry<K, V> header;
这就是有问题的链表。
https://stackoverflow.com/questions/5080612
复制相似问题