Initializing HashSet in Java
Last Updated :
17 Mar, 2022
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.
Java
import java.util.*;
public class Set_example {
public static void main(String[] args)
{
Integer arr[] = { 5 , 6 , 7 , 8 , 1 , 2 , 3 , 4 , 3 };
Set<Integer> set = Collections.<Integer> emptySet();
Collections.addAll(set =
new HashSet<Integer>(Arrays.asList(arr)));
Set<Integer> set2 =
Collections.unmodifiableSet( new HashSet<Integer>
(Arrays.asList(arr)));
System.out.println(set);
}
}
|
Method 3: using .add() each time
Create a set and using .add() method we add the elements into the set
Java
import java.util.*;
public class Set_example {
public static void main(String[] args)
{
Set<Integer> set = new HashSet<Integer>();
set.add( 1 );
set.add( 2 );
set.add( 3 );
set.add( 4 );
set.add( 5 );
set.add( 6 );
set.add( 7 );
set.add( 8 );
set.add( 3 );
System.out.println(set);
}
}
|
Output:
[1, 2, 3, 4, 5, 6, 7, 8]
Share your thoughts in the comments
Please Login to comment...