继承自 HashSet,不过比 HashSet 多的功能是它维护了一份双向链表,来将它所有的元素连接起来。遍历的顺序与插入的顺序是一致的。HashSet 不能保证这样的一致性。
看 LinkedHashSet 的源码,发现 LinkedHashSet 没有自己的方法,只有一些构造方法:
public LinkedHashSet(int initialCapacity, float loadFactor) {
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); }
在这个构造方法中,dummy 的参数专门用来表示这个函数使用 LinkedHashMap,而不是 HashMap。一般我们自己使用 HashSet 的时候不会使用这个构造函数。所以可以这么理解:在HashSet 里面使用 LinkedHashMap 所谓底层实现,就是为了能够让 LinkedHashSet 可以直接继承 HashSet.
总结:
1. LinkedHashSet 继承自 HashSet。
2. HashSet 通常使用 HashMap 作为底层实现,而 LinkedHashSet 使用 LinkedHashMap 作为底层实现,就是为了使用双向链表来保证访问顺序与插入顺序一致。
参考链接:
1. https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashSet.html