HashSet原理与源码分析

HashSet 原理与源码分析

1、原理

2、源码分析

2.1、构造方法

1
2
3
4
//底层采用HashMap实现,只取HashMap存放key的一列
public HashSet() {
map = new HashMap<>();
}

2.2、其他方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//由于HashSet底层采用HashMap实现,所以HashSet底层同样采用HashMap的方法。
//HashSet只使用map中保存key的一列,PRESENT用来填充value一列的值
private static final Object PRESENT = new Object();
public int size() {
return map.size();
}
public boolean isEmpty() {
return map.isEmpty();
}
public boolean contains(Object o) {
return map.containsKey(o);
}
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
public boolean remove(Object o) {
return map.remove(o)==PRESENT;
}
public void clear() {
map.clear();
}