Skip to content

Commit ab14416

Browse files
committed
✨ Introducing new features. HashSet
1 parent 1f4f6d6 commit ab14416

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

MD/collection/HashSet.md

+25-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,31 @@
1919

2020
## 构造函数
2121

22+
```
23+
public HashSet() {
24+
map = new HashMap<>();
25+
}
26+
27+
public HashSet(int initialCapacity, float loadFactor) {
28+
map = new HashMap<>(initialCapacity, loadFactor);
29+
}
30+
```
31+
构造函数很简单,利用了 `HashMap` 初始化了 `map`
32+
2233
## add
2334

24-
## get
35+
```java
36+
public boolean add(E e) {
37+
return map.put(e, PRESENT)==null;
38+
}
39+
```
40+
41+
比较关键的就是这个 `add()` 方法。
42+
可以看出它是将存放的对象当做了 `HashMap` 的健,`value` 都是相同的 `PRESENT` 。由于 `HashMap``key` 是不能重复的,所以每当有重复的值写入到 `HashSet` 时,`value` 会被覆盖,但 `key` 不会收到影响,这样就保证了 `HashSet` 中只能存放不重复的元素。
43+
44+
## 总结
45+
46+
`HashSet` 的原理比较简单,几乎全部借助于 `HashMap` 来实现的。
47+
48+
所以 `HashMap` 会出现的问题 `HashSet` 依然不能避免。
2549

0 commit comments

Comments
 (0)