Skip to content

Commit e9705ac

Browse files
committed
implement HashSet
1 parent b8d4e3f commit e9705ac

1 file changed

Lines changed: 70 additions & 0 deletions

File tree

‎src/data_structure/HashSet.java‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package data_structure;
2+
3+
public class HashSet<V> {
4+
5+
private static final Object EMPTY_VALUE = new Object();
6+
7+
private final HashMap<V, Object> hashMap;
8+
9+
public HashSet() {
10+
this.hashMap = new HashMap<>();
11+
}
12+
13+
public void add(V value) {
14+
hashMap.put(value, EMPTY_VALUE);
15+
}
16+
17+
public boolean contains(V value) {
18+
return hashMap.contains(value);
19+
}
20+
21+
public boolean delete(V value) {
22+
if (hashMap.contains(value)) {
23+
hashMap.delete(value);
24+
return true;
25+
}
26+
return false;
27+
}
28+
29+
public int size() {
30+
return hashMap.entrySet().size();
31+
}
32+
33+
/*
34+
* for test
35+
* */
36+
public void print() {
37+
hashMap.entrySet().forEach(entry -> {
38+
System.out.println("value : " + entry.getKey());
39+
});
40+
}
41+
42+
public static void main(String[] args) {
43+
HashSet<String> stringSet = new HashSet<>();
44+
45+
stringSet.add("contents");
46+
stringSet.add("valuable");
47+
stringSet.add("mvp");
48+
stringSet.add("claude");
49+
stringSet.add("gpt");
50+
stringSet.add("valuable");
51+
52+
stringSet.print();
53+
System.out.println("size = " + stringSet.size());
54+
System.out.println("--- cut ---");
55+
56+
stringSet.delete("valuable");
57+
stringSet.delete("none value");
58+
59+
stringSet.print();
60+
System.out.println("size = " + stringSet.size());
61+
System.out.println("--- cut ---");
62+
63+
stringSet.add("valuable");
64+
stringSet.add("none value");
65+
66+
stringSet.print();
67+
System.out.println("size = " + stringSet.size());
68+
System.out.println("--- cut ---");
69+
}
70+
}

0 commit comments

Comments
 (0)