In this article we will discuss how to convert a HashSet in to an array.
Each collection that provides a member function toArray() i.e.
public <T> T[] toArray(T[] a)
It iterates through all the elements of Collection (HashSet in our case) and set the each elements in the passed argument array []a. But if array [] a ‘s length is less than the Collection’s size then it will create a new array of required size and initialize elements in it.
Checkout the following example to convert HashSet into an array.
Frequently Asked:
package com.thispointer.java.collections.hashsets; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; public class Example5 { public static void main(String[] args) { // Create a new Set of String objects HashSet<String> setOfStrs = new HashSet<>(); // Add elements to a HashSet setOfStrs.add("hello"); setOfStrs.add("abc"); setOfStrs.add("time"); setOfStrs.add("Hi"); // Create an array of size equivalent to Set size // String [] arrOfStrs = new String[setOfStrs.size()]; String[] arrOfStrs = new String[5]; // Initialize the array. String[] recvArr = setOfStrs.toArray(arrOfStrs); // Print the Set for (String data : recvArr) System.out.println(data); } }
Output:
Hi abc hello time null
As you can see the last element is null. It is because we created the array of size 5 but in HashSet there were only 4 elements. Remaining elements in array will be set to null.
[showads ad=inside_post]
Remember if passed array’s length is less than the Collection’s size then it will internally create a new array of required size, then set elements in it and then returns it. Therefore, always use the array returned by toArray() not the array passed.