@kiraSally
2017-07-24 10:52 字数 2522 阅读 0 LinkedHashSet一文同
JAVA COLLECTIONS 源码
1.什么是LinkedHashSet
- 迭代有序,非重复,非线程安全的HashSet,底层数据结构为
LinkedHashMap - 相比于HashSet,LinkedHashSet多维护着一个运行于所有条目的双重链接列表(doubly-linked list )
- 此链接列表定义了迭代顺序,该迭代顺序可为插入顺序或是访问顺序(参见
LinkedHashMap) - 适用于存储有序的不重复值的场景,同时也是一个多态的典型实例
2.LinkedHashSet的数据结构
- 类定义
public class LinkedHashSet<E>extends HashSet<E>implements Set<E>, Cloneable, java.io.Serializable
- HashSet的friendly构造器 -- 重点: LinkedHashSet的实现原理
/*** 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.* LinkedHashSet独享该构造器,同时底层维护一个LinkedHashMap:* -- 借用其的迭代有序和key不重复特性* 因此在LinkedHashSet中只有其构造器的实现* @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<>(initialCapacity, loadFactor);}
- 构造器
/*** Constructs a new, empty linked hash set with the specified initial* capacity and load factor.* 底层会调用父类的构造方法,构造一个有指定初始容量和加载因子的LinkedHashMap实例* @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).* 底层会调用父类的构造方法,构造一个带指定初始容量和默认加载因子0.75的LinkedHashMap实例* @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).* 底层会调用父类的构造方法,构造一个带默认初始容量16和加载因子0.75的LinkedHashMap实例*/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).* 底层会调用父类的构造方法,构造一个足以包含指定collection中所有元素的初始容量和加载因子为0.75的LinkedHashMap实例* @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);}
查看更早的 5 条回复
回复批注
