-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathHashSetCustom.java
66 lines (50 loc) · 1.28 KB
/
HashSetCustom.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package Sets;
import java.util.*;
import java.util.function.Consumer;
import Maps.HashMapCustom;
public class HashSetCustom<E> implements Iterable<E> {
public HashSetCustom() {
}
private HashMapCustom<E, Object> map = new HashMapCustom<>();
private final Object obj = new Object();
public boolean add(E val) {
return map.put(val, obj);
}
public void clear() {
map.clear();
}
public boolean contains(E val) {
return map.containsKey(val);
}
public E remove(E val) throws Exception {
return (E) map.remove(val);
}
public int size() {
return map.size();
}
@Override
public String toString() {
return Arrays.toString(map.toKeyArray());
}
public void forEach(Consumer<? super E> o) {
map.forEach((k, v) -> {
o.accept(k);
});
}
@Override
public Iterator<E> iterator() {
return new HashSetItr();
}
private class HashSetItr implements Iterator<E> {
private Object[] arr = map.toKeyArray();
int cursor = 0;
@Override
public boolean hasNext() {
return cursor < arr.length;
}
@Override
public E next() {
return (E) arr[cursor++];
}
}
}