总结 HashSet:

HashSet的底层是HashMap
并且HashSet中的set相当于在HashMap的key,而value则是new Object出来的常量
扩容条件则是按照HashMap的扩容规则进扩容

源码

  1. public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, java.io.Serializable {
  2. @java.io.Serial
  3. static final long serialVersionUID = -5024744406713321676L; // 序列化版本号
  4. private transient HashMap<E,Object> map; // 底层采用HashMap进行存储
  5. private static final Object PRESENT = new Object(); // 作为HashMap中的value常量,而key则是真正set要存的数据
  6. public HashSet() {
  7. map = new HashMap<>(); // 直接创建一个HashMap
  8. }
  9. public HashSet(Collection<? extends E> c) { // 传入一个集合
  10. map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16)); // 创建一个带初始容量的HashMap
  11. addAll(c); // 将集合c中的元素添加进map中
  12. }
  13. public HashSet(int initialCapacity, float loadFactor) {
  14. map = new HashMap<>(initialCapacity, loadFactor); // 带初始容量和扩容因子的map
  15. }
  16. public HashSet(int initialCapacity) {
  17. map = new HashMap<>(initialCapacity); // 带初始容量的map
  18. }
  19. HashSet(int initialCapacity, float loadFactor, boolean dummy) { // 只在内部使用的构造方法,创建一个LinkedHashMap
  20. map = new LinkedHashMap<>(initialCapacity, loadFactor);
  21. }
  22. public Iterator<E> iterator() {
  23. return map.keySet().iterator();
  24. }
  25. public int size() {
  26. return map.size(); //返回map存有多少个元素
  27. }
  28. public boolean isEmpty() {
  29. return map.isEmpty(); // 判断map是否为空
  30. }
  31. public boolean contains(Object o) {
  32. return map.containsKey(o); // 判断o是否在map中
  33. }
  34. public boolean add(E e) {
  35. return map.put(e, PRESENT)==null;// 添加元素,将数据作为key
  36. }
  37. public boolean remove(Object o) {
  38. return map.remove(o)==PRESENT; // 移除元素
  39. }
  40. public void clear() {
  41. map.clear(); // 清空map
  42. }
  43. @SuppressWarnings("unchecked")
  44. public Object clone() {
  45. try {
  46. HashSet<E> newSet = (HashSet<E>) super.clone(); // 拷贝HashSet
  47. newSet.map = (HashMap<E, Object>) map.clone(); // 拷贝map将map赋值给上面拷贝的HashSet中
  48. return newSet; // 返回set
  49. } catch (CloneNotSupportedException e) {
  50. throw new InternalError(e);
  51. }
  52. }
  53. // 序列化
  54. @java.io.Serial
  55. private void writeObject(java.io.ObjectOutputStream s)
  56. throws java.io.IOException {
  57. s.defaultWriteObject();
  58. s.writeInt(map.capacity());
  59. s.writeFloat(map.loadFactor());
  60. s.writeInt(map.size());
  61. for (E e : map.keySet())
  62. s.writeObject(e);
  63. }
  64. // 反序列化
  65. @java.io.Serial
  66. private void readObject(java.io.ObjectInputStream s)
  67. throws java.io.IOException, ClassNotFoundException {
  68. s.defaultReadObject();
  69. int capacity = s.readInt();
  70. if (capacity < 0) {
  71. throw new InvalidObjectException("Illegal capacity: " + capacity);
  72. }
  73. float loadFactor = s.readFloat();
  74. if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
  75. throw new InvalidObjectException("Illegal load factor: " + loadFactor);
  76. }
  77. int size = s.readInt();
  78. if (size < 0) {
  79. throw new InvalidObjectException("Illegal size: " + size);
  80. }
  81. capacity = (int) Math.min(size * Math.min(1 / loadFactor, 4.0f), HashMap.MAXIMUM_CAPACITY);
  82. SharedSecrets.getJavaObjectInputStreamAccess().checkArray(s, Map.Entry[].class, HashMap.tableSizeFor(capacity));
  83. map = (((HashSet<?>)this) instanceof LinkedHashSet ? new LinkedHashMap<>(capacity, loadFactor) : new HashMap<>(capacity, loadFactor));
  84. for (int i=0; i<size; i++) {
  85. @SuppressWarnings("unchecked")
  86. E e = (E) s.readObject();
  87. map.put(e, PRESENT);
  88. }
  89. }
  90. public Spliterator<E> spliterator() {
  91. return new HashMap.KeySpliterator<>(map, 0, -1, 0, 0); // 获取key的迭代器
  92. }
  93. @Override
  94. public Object[] toArray() {
  95. return map.keysToArray(new Object[map.size()]); // map的key转换为数组
  96. }
  97. @Override
  98. public <T> T[] toArray(T[] a) {
  99. return map.keysToArray(map.prepareArray(a)); // 带泛型的转换key为数组
  100. }
  101. }