1import java.util.HashSet;
2public class HashSetRemoveObjectMethodExample
3{
4 public static void main(String[] args)
5 {
6 HashSet<String> hs = new HashSet<String>();
7 hs.add("hello");
8 hs.add("world");
9 hs.add("java");
10 System.out.println("HashSet before using remove(Object o) method: " + hs);
11 // remove string "world" from HashSet
12 boolean bool = hs.remove("world");
13 System.out.println("Has string removed? " + bool);
14 System.out.println("HashSet after using remove(Object o) method: " + hs);
15 }
16}
1example on removeAll() method for NullPointerException
2import java.util.HashSet;
3public class HashSetRemoveAllMethodExample
4{
5 public static void main(String[] args)
6 {
7 try
8 {
9 HashSet<Integer> hs1 = new HashSet<Integer>();
10 hs1.add(2);
11 hs1.add(4);
12 hs1.add(6);
13 hs1.add(8);
14 hs1.add(10);
15 // printing hs1
16 System.out.println("HashSet before using removeAll() method: " + hs1);
17 // create another object of HashSet
18 HashSet<Integer> hs2 = null;
19 // printing hs2
20 System.out.println("Elements to be removed: " + hs2);
21 System.out.println("Trying to pass null: ");
22 // removing elements from HashSet
23 // specified in hs2 using removeAll() method
24 hs1.removeAll(hs2);
25 System.out.println("HashSet after using removeAll() method: " + hs1);
26 }
27 catch(NullPointerException ex)
28 {
29 System.out.println("Exception: " + ex);
30 }
31 }
32}
1import java.util.HashSet;
2public class HashSetRemoveAllMethodExample
3{
4 public static void main(String[] args)
5 {
6 try
7 {
8 HashSet<Integer> hs1 = new HashSet<Integer>();
9 hs1.add(2);
10 hs1.add(4);
11 hs1.add(6);
12 hs1.add(8);
13 hs1.add(10);
14 System.out.println("HashSet before using removeAll() method: " + hs1);
15 // create another HashSet
16 HashSet<Integer> hs2 = new HashSet<Integer>();
17 hs2.add(2);
18 hs2.add(4);
19 hs2.add(6);
20 System.out.println("Elements to be removed: " + hs2);
21 // remove elements from hs1 described in hs2 using removeAll() method
22 hs1.removeAll(hs2);
23 System.out.println("HashSet after using removeAll() method: " + hs1);
24 }
25 catch(NullPointerException ex)
26 {
27 System.out.println("Exception: " + ex);
28 }
29 }
30}