设计哈希集合
// HashSet 基于 HashMap 来实现的,是一个不允许有重复元素的集合。
// HashSet 只允许有一个 null 值。
// HashSet 是无序的,即不会记录插入的顺序。
// HashSet 不是线程安全的,如果多个线程尝试同时修改 HashSet,则最终结果是不确定的。 必须在多线程访问时显式同步对 HashSet 的并发访问。
// HashSet 实现了 Set 接口。
class MyHashSet {
/** Initialize your data structure here. */
private List<Integer> hashSet;
public MyHashSet() {
hashSet = new ArrayList<>();
}
public void add(int key) {
for(int i = 0; i < hashSet.size(); i++){
if(key == hashSet.get(i)){
// 重复的元素不会被添加
return;
}
}
hashSet.add(key);
}
public void remove(int key) {
for(int i = 0; i < hashSet.size(); i++){
if(key == hashSet.get(i)){
hashSet.remove(i);
}
}
}
/** Returns true if this set contains the specified element */
public boolean contains(int key) {
for(int i = 0; i < hashSet.size(); i++){
if(key == hashSet.get(i)){
return true;
}
}
return false;
}
}
/**
* Your MyHashSet object will be instantiated and called as such:
* MyHashSet obj = new MyHashSet();
* obj.add(key);
* obj.remove(key);
* boolean param_3 = obj.contains(key);
*/