Open In App

Convert HashSet to array in Java

Last Updated : 11 Dec, 2020
Comments
Improve
Suggest changes
1 Like
Like
Report

Java HashSet class is used to create a collection that uses a hash table for the storage of elements. It inherits AbstractSet class and implements Set Interface

The key points about HashSet are:

  • HashSet contains unique elements only.
  • HashSet allows null values.
  • The insertion of elements in a HashSet is based on a hashcode.
  • HashSet is best used for searching problems.

There are two ways of converting HashSet to the array:

  1. Traverse through the HashSet and add every element to the array.
  2. To convert a HashSet into an array in java, we can use the function of toArray().

Method 1: By traversing the set add elements to the array

We can traverse the Set using a simple for loop and then add elements one by one to the array.


Output
Hash Set Contains :[1, 13, 27, 19, 87]
1
13
27
19
87

Method 2: Using toArray() method

Syntax:

public Object[] toArray()
           or
public <T> T[] toArray(T[] a)

Parameters: This method either accepts no parameters or it takes an array T[] a as a parameter which is the array into which the elements of the list are to be stored if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.

Return Value: The function returns an array containing all the elements in this list.


Output
Hash Set Contains :[1, 13, 27, 19, 87]
1
13
27
19
87

Article Tags :
Practice Tags :

Similar Reads