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.

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.

Output:

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.

 

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.

Click Here to Subscribe for more Articles / Tutorials like this.