Program to initialize HashSet values using Constructor in Java

Java




// Java Program to intitalise the values of HashSet 
// Using Arrays.asList method
import java.util.*;
import java.util.HashSet;
import java.util.Arrays;
  
class GFG {
    public static void main (String[] args) {
      // Initialize HashSet using Constructor
        HashSet<String>myhashset=new HashSet<>(Arrays.asList("green", "white", "GFG"));  
                                         
        
      //printing hashset values
      System.out.println("HashSet Initialized Using Constructor: " +myhashset);
    }
}


Output

HashSet Initialized Using Constructor: [green, white, GFG]


Explanation of the above Program:

  • In the above example, we have initialized a HashSet named myhashset.
  • We have initialized this using a constructor in which we have passed some values as an argument with Arrays.asList() method.
  • At last, it prints the values of the HashSet.

How to Initialize HashSet Values Using Constructor in Java?

In Java programming, HashSet is a collection framework that is implemented by the HashSet class. It only contains unique elements and does not allow duplicate values. Mainly it does not maintain any insertion order but is inserted based on hash code.

We can initialize HashSet values in many ways in Java. But in this article, we will discuss how to initialize HashSet values using Constructor in Java.

Method: Using Constructor and Arrays.asList( ) method

By using the constructor along with Arrays.asList() method we can initialize HashSet values. Below is the syntax of this for a clear understanding of the concept.

Syntax:

 HashSet<String>myhashset=new HashSet<>(Arrays.asList(" "));

Here, myhashset is the name of the HashSet created.

Similar Reads

Program to initialize HashSet values using Constructor in Java

Java // Java Program to intitalise the values of HashSet  // Using Arrays.asList method import java.util.*; import java.util.HashSet; import java.util.Arrays;    class GFG {     public static void main (String[] args) {       // Initialize HashSet using Constructor         HashSetmyhashset=new HashSet<>(Arrays.asList("green", "white", "GFG"));                                                            //printing hashset values       System.out.println("HashSet Initialized Using Constructor: " +myhashset);     } }...

Contact Us