8000 add a demo for HashSet · fishercoder1534/RandomJava@75ac905 · GitHub
[go: up one dir, main page]

Skip to content

Commit 75ac905

Browse files
add a demo for HashSet
1 parent 3c615de commit 75ac905

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package java_collections;
2+
3+
import java.util.HashSet;
4+
import java.util.Set;
5+
6+
public class HashSetDemo {
7+
8+
private static final int NUMBER_OF_SET_ENTRIES = 2;
9+
10+
public static void main(String... args) {
11+
System.out.println("Program started.");
12+
HashSetDemo hashSetDemo = new HashSetDemo();
13+
hashSetDemo.understandHashSetInternalWorkings();
14+
System.out.println("Program finished.");
15+
}
16+
17+
private void understandHashSetInternalWorkings() {
18+
/**
19+
* 1. Internally, Java uses a HashMap to implement HashSet, it just inserts a dummy object as value into the map: private static final Object PRESENT = new Object();
20+
* you can step into the java.util.HashSet library to see this:
21+
* public boolean add(E e) {
22+
* return map.put(e, PRESENT)==null;
23+
* }
24+
* 2. https://medium.com/javarevisited/internal-working-of-hashset-in-java-interview-question-129bdd31fc60 for more references/
25+
* */
26+
Set<String> set = new HashSet<>();
27+
for (int i = 0; i < NUMBER_OF_SET_ENTRIES; i++) {
28+
set.add(i + "");
29+
}
30+
System.out.println("Method finishes.");
31+
}
32+
}

0 commit comments

Comments
 (0)
0