本文中关于
LinkedHashMap
的部分参考源码阅读 - LinkedHashMap
0. LinkedHashSet是什么
-
LinkedHashSet
继承自HashSet
- 通过
LinkedHashMap
实现
1. 实现原理
在LinkedHashSet
的构造函数中均调用了
super(initialCapacity, loadFactor, true);
即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<>(initialCapacity, loadFactor);
}
所以LinkedHashSet
可以按照插入顺序来遍历,但是不能按照访问顺序遍历。
网友评论