Java Code Example: convert HashSet to Array

This program creates a HashSet collection of 5 months (Jan, Feb, Mar, Apr, May) and then converts it to an array using toArray() method. The array is then printed using Arrays.toString() method. The output will be a string representation of the array elements, e.g. [January, February, March, April, May].

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]