java 中的集合(十) LinkedHashSet源码分析

时间:2021-09-02 15:25:42

LinkedHashSet实现了Set接口,由记录顺序的哈希表(实际上是一个LinkedHashMap实例,LinkedHashMap参考:链接)支持。相比HashSet,它记录了set的顺序。LinkedHashSet也允许使用null元素(很显然,LinkedHashMap也允许使用空值key)。

LinkedHashSet继承于HashSet(同样的,LinkedHashMap继承于HashMap),所以基本上和HashSet类似。(HashSet参考:链接

来看看源码:

public class LinkedHashSet<E>
extends HashSet<E>
implements Set<E>, Cloneable, java.io.Serializable {

private static final long serialVersionUID = -2851667679971038690L;

/**
* 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中的这个方法:

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

由于LinkedHashMap记录key的顺序,所以LinkedHashSet自然是有序的。

另外,注意一下,在初始化时,若将Collection作为参数,对Map初始大小设置的区别。

这个是HashSet的:

  public HashSet(Collection<? extends E> c) {
map = new HashMap<E,Object>(Math.max((int) (c.size()/.75f) + 1, 16));
addAll(c);
}

这个是LinkedHashSet的:

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

由于LinkedHashMap和HashMap,都采用了和HashSet类似的方法,这让LinkedHashSet显得比较特殊。(而且似乎应该把11换成16,不然和HashTable类似了)

同时看看ArrayList的:

  public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
size = elementData.length;
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
}

ArrayList没有载入因子,初始化时没有扩容。


参考地址:http://blog.csdn.net/u010156024/article/details/48394475