关于 LinkedHashSet

  • LinkedHashSet 是 HashSet 的子类;
  • LinkedHashSet 底层是一个 LinkedHashMap,底层维护了一个数组+双向链表;
  • LinkedHashSet 根据元素的 hashCode 值来决定元素的存储位置,同时使用链表维护元素的次序,使得元素看起来是以插入顺序保存的;
  • LinkedHashSet 不允许添加重复元素;
  • LinkedHashSet 是有序的。
    1. public class LinkedHashSet<E>
    2. extends HashSet<E>
    3. implements Set<E>, Cloneable, java.io.Serializable {

在 LinkedHashSet 中维护了一个 hash 表和双向链表( LinkedHashSet 有 head 和 tail )。
每一个节点有 pre 和 next 属性,这样可以形成双向链表。
在添加一个元素时,先求 hash 值,再求索引,确定该元素在 hashtable 的位置,然后将添加的元素加入到双向链表(如果已经存在,不添加,原则和 HashSet 一样)。

构造器

image.png

  1. /**
  2. * Constructs a new, empty linked hash set with the specified initial
  3. * capacity and load factor.
  4. *
  5. * @param initialCapacity the initial capacity of the linked hash set
  6. * @param loadFactor the load factor of the linked hash set
  7. * @throws IllegalArgumentException if the initial capacity is less
  8. * than zero, or if the load factor is nonpositive
  9. */
  10. public LinkedHashSet(int initialCapacity, float loadFactor) {
  11. super(initialCapacity, loadFactor, true);
  12. }
  13. /**
  14. * Constructs a new, empty linked hash set with the specified initial
  15. * capacity and the default load factor (0.75).
  16. *
  17. * @param initialCapacity the initial capacity of the LinkedHashSet
  18. * @throws IllegalArgumentException if the initial capacity is less
  19. * than zero
  20. */
  21. public LinkedHashSet(int initialCapacity) {
  22. super(initialCapacity, .75f, true);
  23. }
  24. /**
  25. * Constructs a new, empty linked hash set with the default initial
  26. * capacity (16) and load factor (0.75).
  27. */
  28. public LinkedHashSet() {
  29. super(16, .75f, true);
  30. }
  31. /**
  32. * Constructs a new linked hash set with the same elements as the
  33. * specified collection. The linked hash set is created with an initial
  34. * capacity sufficient to hold the elements in the specified collection
  35. * and the default load factor (0.75).
  36. *
  37. * @param c the collection whose elements are to be placed into
  38. * this set
  39. * @throws NullPointerException if the specified collection is null
  40. */
  41. public LinkedHashSet(Collection<? extends E> c) {
  42. super(Math.max(2*c.size(), 11), .75f, true);
  43. addAll(c);
  44. }

源码

  1. package java.util;
  2. /**
  3. * <p>Hash table and linked list implementation of the <tt>Set</tt> interface,
  4. * with predictable iteration order. This implementation differs from
  5. * <tt>HashSet</tt> in that it maintains a doubly-linked list running through
  6. * all of its entries. This linked list defines the iteration ordering,
  7. * which is the order in which elements were inserted into the set
  8. * (<i>insertion-order</i>). Note that insertion order is <i>not</i> affected
  9. * if an element is <i>re-inserted</i> into the set. (An element <tt>e</tt>
  10. * is reinserted into a set <tt>s</tt> if <tt>s.add(e)</tt> is invoked when
  11. * <tt>s.contains(e)</tt> would return <tt>true</tt> immediately prior to
  12. * the invocation.)
  13. *
  14. * <p>This implementation spares its clients from the unspecified, generally
  15. * chaotic ordering provided by {@link HashSet}, without incurring the
  16. * increased cost associated with {@link TreeSet}. It can be used to
  17. * produce a copy of a set that has the same order as the original, regardless
  18. * of the original set's implementation:
  19. * <pre>
  20. * void foo(Set s) {
  21. * Set copy = new LinkedHashSet(s);
  22. * ...
  23. * }
  24. * </pre>
  25. * This technique is particularly useful if a module takes a set on input,
  26. * copies it, and later returns results whose order is determined by that of
  27. * the copy. (Clients generally appreciate having things returned in the same
  28. * order they were presented.)
  29. *
  30. * <p>This class provides all of the optional <tt>Set</tt> operations, and
  31. * permits null elements. Like <tt>HashSet</tt>, it provides constant-time
  32. * performance for the basic operations (<tt>add</tt>, <tt>contains</tt> and
  33. * <tt>remove</tt>), assuming the hash function disperses elements
  34. * properly among the buckets. Performance is likely to be just slightly
  35. * below that of <tt>HashSet</tt>, due to the added expense of maintaining the
  36. * linked list, with one exception: Iteration over a <tt>LinkedHashSet</tt>
  37. * requires time proportional to the <i>size</i> of the set, regardless of
  38. * its capacity. Iteration over a <tt>HashSet</tt> is likely to be more
  39. * expensive, requiring time proportional to its <i>capacity</i>.
  40. *
  41. * <p>A linked hash set has two parameters that affect its performance:
  42. * <i>initial capacity</i> and <i>load factor</i>. They are defined precisely
  43. * as for <tt>HashSet</tt>. Note, however, that the penalty for choosing an
  44. * excessively high value for initial capacity is less severe for this class
  45. * than for <tt>HashSet</tt>, as iteration times for this class are unaffected
  46. * by capacity.
  47. *
  48. * <p><strong>Note that this implementation is not synchronized.</strong>
  49. * If multiple threads access a linked hash set concurrently, and at least
  50. * one of the threads modifies the set, it <em>must</em> be synchronized
  51. * externally. This is typically accomplished by synchronizing on some
  52. * object that naturally encapsulates the set.
  53. *
  54. * If no such object exists, the set should be "wrapped" using the
  55. * {@link Collections#synchronizedSet Collections.synchronizedSet}
  56. * method. This is best done at creation time, to prevent accidental
  57. * unsynchronized access to the set: <pre>
  58. * Set s = Collections.synchronizedSet(new LinkedHashSet(...));</pre>
  59. *
  60. * <p>The iterators returned by this class's <tt>iterator</tt> method are
  61. * <em>fail-fast</em>: if the set is modified at any time after the iterator
  62. * is created, in any way except through the iterator's own <tt>remove</tt>
  63. * method, the iterator will throw a {@link ConcurrentModificationException}.
  64. * Thus, in the face of concurrent modification, the iterator fails quickly
  65. * and cleanly, rather than risking arbitrary, non-deterministic behavior at
  66. * an undetermined time in the future.
  67. *
  68. * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
  69. * as it is, generally speaking, impossible to make any hard guarantees in the
  70. * presence of unsynchronized concurrent modification. Fail-fast iterators
  71. * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
  72. * Therefore, it would be wrong to write a program that depended on this
  73. * exception for its correctness: <i>the fail-fast behavior of iterators
  74. * should be used only to detect bugs.</i>
  75. *
  76. * <p>This class is a member of the
  77. * <a href="{@docRoot}/../technotes/guides/collections/index.html">
  78. * Java Collections Framework</a>.
  79. *
  80. * @param <E> the type of elements maintained by this set
  81. *
  82. * @author Josh Bloch
  83. * @see Object#hashCode()
  84. * @see Collection
  85. * @see Set
  86. * @see HashSet
  87. * @see TreeSet
  88. * @see Hashtable
  89. * @since 1.4
  90. */
  91. public class LinkedHashSet<E>
  92. extends HashSet<E>
  93. implements Set<E>, Cloneable, java.io.Serializable {
  94. private static final long serialVersionUID = -2851667679971038690L;
  95. /**
  96. * Constructs a new, empty linked hash set with the specified initial
  97. * capacity and load factor.
  98. *
  99. * @param initialCapacity the initial capacity of the linked hash set
  100. * @param loadFactor the load factor of the linked hash set
  101. * @throws IllegalArgumentException if the initial capacity is less
  102. * than zero, or if the load factor is nonpositive
  103. */
  104. public LinkedHashSet(int initialCapacity, float loadFactor) {
  105. super(initialCapacity, loadFactor, true);
  106. }
  107. /**
  108. * Constructs a new, empty linked hash set with the specified initial
  109. * capacity and the default load factor (0.75).
  110. *
  111. * @param initialCapacity the initial capacity of the LinkedHashSet
  112. * @throws IllegalArgumentException if the initial capacity is less
  113. * than zero
  114. */
  115. public LinkedHashSet(int initialCapacity) {
  116. super(initialCapacity, .75f, true);
  117. }
  118. /**
  119. * Constructs a new, empty linked hash set with the default initial
  120. * capacity (16) and load factor (0.75).
  121. */
  122. public LinkedHashSet() {
  123. super(16, .75f, true);
  124. }
  125. /**
  126. * Constructs a new linked hash set with the same elements as the
  127. * specified collection. The linked hash set is created with an initial
  128. * capacity sufficient to hold the elements in the specified collection
  129. * and the default load factor (0.75).
  130. *
  131. * @param c the collection whose elements are to be placed into
  132. * this set
  133. * @throws NullPointerException if the specified collection is null
  134. */
  135. public LinkedHashSet(Collection<? extends E> c) {
  136. super(Math.max(2*c.size(), 11), .75f, true);
  137. addAll(c);
  138. }
  139. /**
  140. * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
  141. * and <em>fail-fast</em> {@code Spliterator} over the elements in this set.
  142. *
  143. * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
  144. * {@link Spliterator#DISTINCT}, and {@code ORDERED}. Implementations
  145. * should document the reporting of additional characteristic values.
  146. *
  147. * @implNote
  148. * The implementation creates a
  149. * <em><a href="Spliterator.html#binding">late-binding</a></em> spliterator
  150. * from the set's {@code Iterator}. The spliterator inherits the
  151. * <em>fail-fast</em> properties of the set's iterator.
  152. * The created {@code Spliterator} additionally reports
  153. * {@link Spliterator#SUBSIZED}.
  154. *
  155. * @return a {@code Spliterator} over the elements in this set
  156. * @since 1.8
  157. */
  158. @Override
  159. public Spliterator<E> spliterator() {
  160. return Spliterators.spliterator(this, Spliterator.DISTINCT | Spliterator.ORDERED);
  161. }
  162. }