【转载】原文链接
1. 概述
Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.)
LinkedHashSet是基于HashMap和双向链表的实现。
1 | LinkedHashSet<String> lset = new LinkedHashSet<String>(); |
利用链表来记录,保证了迭代输出的有序性。其具体结构如下所示:

可以看出,其实现基本和LinkedHashMap一样。
2. 关键实现
1 | public class LinkedHashSet<E> |
从继承关系来看就知道LinkedHashMap的实现非常简单,就是集成HashSet的接口,并且在构造时调用的是:
1 | HashSet(int initialCapacity, float loadFactor, boolean dummy) { |
因此,结构也便是如HashSet于HashMap一样,LinkedHashSet也便如LinkedHashMap一样,只是将Value做了一个dummy的object。