
How can we use HashSet in java program?

The hashSet class is used to create a collection and store it in a hash table. Each collection refer to a unique value.
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class SetExample {
public static void main(String[] args) {
Set set = new HashSet();
boolean[] flags = new boolean[10];
flags[0] = set.add("Naulej");
flags[1] = set.add("Rose");
flags[2] = set.add("Naulej");
flags[3] = set.add(2376326);
flags[4] = set.add("India");
flags[5] = set.add(new Integer(10));
flags[6] = set.add(new Long(5));
flags[7] = set.add('T');
flags[8] = set.add("India");
for (int i = 0; i < flags.length; i++) {
boolean b = flags[i];
System.out.println("value at " + i + " - " + b);
}
System.out.println(set);
}
}
Output:-
value at 0 - true value at 1 - true value at 2 - false value at 3 - true value at 4 - true value at 5 - true value at 6 - true value at 7 - true value at 8 - false value at 9 â?? false [T, 5, Naulej, 10, Rose, 2376326, India]
Description:- The above example demonstrates you the Set interface. Since Set is an interface, you need to instantiate a concrete implementation of the interface in order to use it. Here Set is implemented by its subclass HashSet. Set does not accept duplicate values. So here we have check whether the added elements are duplicate or not. We have created a Boolean array and store the Set elements to it. If the elements is previously exists in Set, it will display false, otherwise it will display true.
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.