整体源码很少,内部有一个 HashMap,所有操作都是操作的 内部的 HashMap。它简化了 HashMap 的功能,只能存储 key,默认有一个 value。

    1. public class HashSet<E>
    2. extends AbstractSet<E>
    3. implements Set<E>, Cloneable, java.io.Serializable
    4. {
    5. static final long serialVersionUID = -5024744406713321676L;
    6. private transient HashMap<E,Object> map;
    7. //默认的 value
    8. private static final Object PRESENT = new Object();
    9. public HashSet() {
    10. map = new HashMap<>();
    11. }
    12. public HashSet(Collection<? extends E> c) {
    13. map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
    14. addAll(c);
    15. }
    16. public HashSet(int initialCapacity, float loadFactor) {
    17. map = new HashMap<>(initialCapacity, loadFactor);
    18. }
    19. public HashSet(int initialCapacity) {
    20. map = new HashMap<>(initialCapacity);
    21. }
    22. HashSet(int initialCapacity, float loadFactor, boolean dummy) {
    23. map = new LinkedHashMap<>(initialCapacity, loadFactor);
    24. }
    25. public Iterator<E> iterator() {
    26. return map.keySet().iterator();
    27. }
    28. public int size() {
    29. return map.size();
    30. }
    31. /**
    32. * Returns <tt>true</tt> if this set contains no elements.
    33. *
    34. * @return <tt>true</tt> if this set contains no elements
    35. */
    36. public boolean isEmpty() {
    37. return map.isEmpty();
    38. }
    39. public boolean contains(Object o) {
    40. return map.containsKey(o);
    41. }
    42. public boolean add(E e) {
    43. return map.put(e, PRESENT)==null;
    44. }
    45. /**
    46. * Removes the specified element from this set if it is present.
    47. * More formally, removes an element <tt>e</tt> such that
    48. * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>,
    49. * if this set contains such an element. Returns <tt>true</tt> if
    50. * this set contained the element (or equivalently, if this set
    51. * changed as a result of the call). (This set will not contain the
    52. * element once the call returns.)
    53. *
    54. * @param o object to be removed from this set, if present
    55. * @return <tt>true</tt> if the set contained the specified element
    56. */
    57. public boolean remove(Object o) {
    58. return map.remove(o)==PRESENT;
    59. }
    60. /**
    61. * Removes all of the elements from this set.
    62. * The set will be empty after this call returns.
    63. */
    64. public void clear() {
    65. map.clear();
    66. }
    67. /**
    68. * Returns a shallow copy of this <tt>HashSet</tt> instance: the elements
    69. * themselves are not cloned.
    70. *
    71. * @return a shallow copy of this set
    72. */
    73. @SuppressWarnings("unchecked")
    74. public Object clone() {
    75. try {
    76. HashSet<E> newSet = (HashSet<E>) super.clone();
    77. newSet.map = (HashMap<E, Object>) map.clone();
    78. return newSet;
    79. } catch (CloneNotSupportedException e) {
    80. throw new InternalError(e);
    81. }
    82. }
    83. private void writeObject(java.io.ObjectOutputStream s)
    84. throws java.io.IOException {
    85. // Write out any hidden serialization magic
    86. s.defaultWriteObject();
    87. // Write out HashMap capacity and load factor
    88. s.writeInt(map.capacity());
    89. s.writeFloat(map.loadFactor());
    90. // Write out size
    91. s.writeInt(map.size());
    92. // Write out all elements in the proper order.
    93. for (E e : map.keySet())
    94. s.writeObject(e);
    95. }
    96. private void readObject(java.io.ObjectInputStream s)
    97. throws java.io.IOException, ClassNotFoundException {
    98. // Read in any hidden serialization magic
    99. s.defaultReadObject();
    100. // Read capacity and verify non-negative.
    101. int capacity = s.readInt();
    102. if (capacity < 0) {
    103. throw new InvalidObjectException("Illegal capacity: " +
    104. capacity);
    105. }
    106. // Read load factor and verify positive and non NaN.
    107. float loadFactor = s.readFloat();
    108. if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
    109. throw new InvalidObjectException("Illegal load factor: " +
    110. loadFactor);
    111. }
    112. // Read size and verify non-negative.
    113. int size = s.readInt();
    114. if (size < 0) {
    115. throw new InvalidObjectException("Illegal size: " +
    116. size);
    117. }
    118. // Set the capacity according to the size and load factor ensuring that
    119. // the HashMap is at least 25% full but clamping to maximum capacity.
    120. capacity = (int) Math.min(size * Math.min(1 / loadFactor, 4.0f),
    121. HashMap.MAXIMUM_CAPACITY);
    122. // Constructing the backing map will lazily create an array when the first element is
    123. // added, so check it before construction. Call HashMap.tableSizeFor to compute the
    124. // actual allocation size. Check Map.Entry[].class since it's the nearest public type to
    125. // what is actually created.
    126. SharedSecrets.getJavaOISAccess()
    127. .checkArray(s, Map.Entry[].class, HashMap.tableSizeFor(capacity));
    128. // Create backing HashMap
    129. map = (((HashSet<?>)this) instanceof LinkedHashSet ?
    130. new LinkedHashMap<E,Object>(capacity, loadFactor) :
    131. new HashMap<E,Object>(capacity, loadFactor));
    132. // Read in all elements in the proper order.
    133. for (int i=0; i<size; i++) {
    134. @SuppressWarnings("unchecked")
    135. E e = (E) s.readObject();
    136. map.put(e, PRESENT);
    137. }
    138. }
    139. public Spliterator<E> spliterator() {
    140. return new HashMap.KeySpliterator<E,Object>(map, 0, -1, 0, 0);
    141. }
    142. }