-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashSetProgram.java
More file actions
41 lines (32 loc) · 1.09 KB
/
HashSetProgram.java
File metadata and controls
41 lines (32 loc) · 1.09 KB
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
import java.util.HashSet;
import java.util.Iterator;
public class HashSetProgram {
public static void main(String[] args) {
HashSet<Integer> set = new HashSet<>();
// add
set.add(1);
set.add(3);
set.add(2);
// print set
System.out.println(set);
// print size of set
System.out.println("Size of Set: " + set.size());
// searching in set
if (set.contains(2)) System.out.println("Element found in set.");
else System.out.println("Element not found.");
// removing element from set
set.remove(2);
System.out.println("Set after removing 2: " + set);
set.add(6);
// Iterating through set
Iterator<Integer> it = set.iterator();
while (it.hasNext()) System.out.println(it.next());
// isEmpty
if (set.isEmpty()) System.out.println("Set is Empty.");
else System.out.println("Set is not Empty.");
// Iterating through set using for each loop
for (Integer i: set) {
System.out.println(i);
}
}
}