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 HashSet of 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 HashSet
HashSet<Integer> hashSet = new HashSet<Integer>();
// Use add() method
hashSet.add(11);
hashSet.add(22);
hashSet.add(33);
hashSet.add(44);
// Using toArray() method
Object[] 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.util classes to include the HashSet data structure.

  • In line 7, we initiated an object of empty HashSet of Integers.

  • In lines 9 to 11, we initiated some integers.

  • In line 13, we called the hashSet.toArray() method to represent the hashSet in an array representation and stored it in an Object array.

  • In lines 16 to 17, we implemented a loop in which we print all the Object array elements one by one.

In this way, we can use the hashSet.toArray() method in Java.

Free Resources