变量

1
2
3
private transient HashMap<E,Object> map;
// 传入到HashMap中作为value
private static final Object PRESENT = new Object();

构造函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public HashSet() {
map = new HashMap<>();
}

public HashSet(int initialCapacity) {
map = new HashMap<>(initialCapacity);
}

public HashSet(int initialCapacity, float loadFactor) {
map = new HashMap<>(initialCapacity, loadFactor);
}

public HashSet(Collection<? extends E> c) {
map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
addAll(c);
}

我们可以看到他的构造函数都是再次调用了HashMap的构造函数。将map变量初始化为相应的HashMap

添加

1
2
3
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}

将传入的key,一个空的value。通过map的put操作放值到map中。通过map的key不能重复原理。如果key重复,则不会添加到map中。

迭代器

1
2
3
public Iterator<E> iterator() {
return map.keySet().iterator();
}

通过这里我们可以看出来HashSet的原理就是在HashMap的基础上实现的。

我们只需要他的key集合就是我们所需的HashSet