Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

hashset
java
communitycreator

What is the hashset.toArray() method in Java?

Harsh Jain

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

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]);
}
}
Use hashset.toArray() function in Java

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.

RELATED TAGS

hashset
java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring