What is the hashset.toArray() method in Java?
The hashSet.toArray() function converts the values in a hashset to an array of elements.
How to use hashset.toArray() method in Java
The steps to use the function are mentioned below.
-
Initialize a
HashSetof integers. -
Add some integer elements in it.
-
Call the
hashset.toArray()function and make it print in the console. -
You will see the results in the output section.
Function description
We will initiate an empty HashSet of integers and then add some integers into it.
Next, we will call a toArray() function in which we will pass nothing in parameters. The function will return a hashSet element in a square bracket format present in the hashset.
The result will be printed in the output window.
Code
Let’s look at the code.
import java.util.*;class Main{public static void main(String args[]){// Creating an Empty HashSetHashSet<Integer> hashSet = new HashSet<Integer>();// Use add() methodhashSet.add(11);hashSet.add(22);hashSet.add(33);hashSet.add(44);// Using toArray() methodObject[] arr = hashSet.toArray();System.out.println("The array is:");for (int j = 0; j < arr.length; j++)System.out.println(arr[j]);}}
Explanation
-
In line 1, we imported the
java.utilclasses to include theHashSetdata structure. -
In line 7, we initiated an object of empty
HashSetof Integers. -
In lines 9 to 11, we initiated some integers.
-
In line 13, we called the
hashSet.toArray()method to represent thehashSetin an array representation and stored it in anObjectarray. -
In lines 16 to 17, we implemented a loop in which we print all the
Objectarray elements one by one.
In this way, we can use the hashSet.toArray() method in Java.