Java Code Example: convert HashSet to Array

First, a HashSet is initialized with the months January to May. Then it is converted into an array. The function .toArray() returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array. If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection.

Example 1

import java.util.Arrays;
import java.util.HashSet;

class HashSetToArray {
    public static void main(String[] args) {
        HashSet<String> setMonths = new HashSet<String>();
        setMonths.add("January");
        setMonths.add("February");
        setMonths.add("March");
        setMonths.add("April");
        setMonths.add("May");

        String[] months = setMonths.toArray(new String[setMonths.size()]);

        System.out.println(Arrays.toString(months));
    }
}
Output
[May, March, January, February, April]

Example 2

If this collection fits in the specified array with room to spare (i.e., the array has more elements than this collection), the element in the array immediately following the end of the collection is set to null. (This is useful in determining the length of this collection only if the caller knows that this collection does not contain any null elements.)

import java.util.Arrays;
import java.util.HashSet;

class Cube {
    public static void main(String[] args) {
        HashSet<Integer> setNumbers = new HashSet<Integer>();
        setNumbers.add(10);
        setNumbers.add(20);
        setNumbers.add(30);

        Integer[] numbers = setNumbers.toArray(new Integer[]{1, 2, 3, 4, 5, 6, 7});

        System.out.println(Arrays.toString(numbers));
    }
}
Output
[20, 10, 30, null, 5, 6, 7]