Initializing HashSet in Java
Set in Java is an interface which extends Collection. It is an unordered collection of objects in which duplicate values cannot be stored.
Basically, set is implemented by HashSet, LinkedHashSet or TreeSet (sorted representation).
Set has various methods to add, remove clear, size, etc to enhance the usage of this interface.
Method 1: Using Constructor:
In this method first we create an array then convert it to a list and then pass it to the HashSet constructor that accepts another collection.
Integer elements of the set are printed in sorted order.
Method 2 using Collections:
Collections class consists of several methods that operate on collections.
a) Collection.addAll() : adds all the specified elements to the specified collection of the specified type.
b) Collections.unmodifiableSet() : adds the elements and returns an unmodifiable view of the specified set.
Method 3: using .add() each time
Create a set and using .add() method we add the elements into the set
[1, 2, 3, 4, 5, 6, 7, 8]
This article is contributed by Nikita Tiwari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.