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:
- Traverse through the HashSet and add every element to the array.
- 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.
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
HashSet<String> set = new HashSet<String>();
set.add( "1" );
set.add( "13" );
set.add( "27" );
set.add( "87" );
set.add( "19" );
System.out.println( "Hash Set Contains :" + set);
String arr[] = new String[set.size()];
int i= 0 ;
for (String ele:set){
arr[i++] = ele;
}
for (String n : arr)
System.out.println(n);
}
}
|
OutputHash 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.
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
HashSet<String> set = new HashSet<String>();
set.add( "1" );
set.add( "13" );
set.add( "27" );
set.add( "87" );
set.add( "19" );
System.out.println( "Hash Set Contains :" + set);
String arr[] = new String[set.size()];
set.toArray(arr);
for (String n : arr)
System.out.println(n);
}
}
|
OutputHash Set Contains :[1, 13, 27, 19, 87]
1
13
27
19
87