Java HashSet toArray() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
HashSet

Definition

In Java, toArray() copies the elements of a HashSet into a new array, in the same order the iterator would return them. The array is independent of the set: later changes to either one do not affect the other.

There are two forms. toArray() returns an Object[]. toArray(T[] a) returns an array of the type you pass, which is what you want for String[] or Integer[].

An instance method of java.util.HashSet (class since Java 1.2): a set of unique elements kept in a hash table, with no guaranteed order, one null element allowed, and no thread safety.

Syntax

Without arguments you get Object[]; with an array argument you get your own type.

Java
Set<String> colors = new HashSet<>();
colors.add("red");
Object[] plain = colors.toArray();
String[] typed = colors.toArray(new String[0]);
CallWhat it does
set.toArray()A new Object[] with every element.
set.toArray(new String[0])A String[]; the empty array only supplies the type.
set.toArray(new String[set.size()])Same result; the array you pass is reused because it fits.
new ArrayList<>(set)A List copy that you can sort or index.

Java 11 added toArray(String[]::new) as a shorter form. On Java 8, use toArray(new String[0]).

Library declarations
Java
// Inherited from java.util.AbstractCollection<E>
public Object[] toArray()
public <T> T[] toArray(T[] a)

// Declared in Set<E> and Collection<E>

Parameters

ParameterDescription
a (T[])Second form only: the array to fill if it is big enough. Otherwise a new array of the same runtime type is created. It must not be null.

Return Value

Return ValueDescription
Object[]First form: a new array holding every element.
T[]Second form: a itself when it fits, or a new array of the same type.

Compare with Similar Methods

Copying a set into another structure:

MethodHow it differs
iterator()Walks the elements without copying them.
clone()Copies into another HashSet, not an array.
ArrayList.toArray(...)The same two forms on a list, where the order is meaningful.

Java Examples

Example 1 — Copy a Set into a String Array

Use toArray(new String[0]), sort the array, and show that it is a separate copy.

Java
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class HashSetToArrayDemo {
    public static void main(String[] args) {
        Set<String> colors = new HashSet<>();
        colors.add("red");
        colors.add("green");
        colors.add("blue");

        String[] array = colors.toArray(new String[0]);
        Arrays.sort(array);

        System.out.println("length: " + array.length);
        System.out.println("sorted: " + Arrays.toString(array));

        colors.add("pink");
        System.out.println("array still has " + array.length + " items");
    }
}

How It Works

  1. Type from the argument. The empty String[0] only tells toArray which array type to create; the method allocates one of length 3.
  2. Sort the copy. The array follows hash order, so Arrays.sort puts it in alphabetical order for a stable printout.
  3. A snapshot. Adding "pink" to the set afterwards changes the set, but the array keeps its three items.
  4. Array vs set size. array.length is a field fixed at creation, while the set can keep growing.

Example 2 — toArray() Returns Object[], and the Cast Fails

Add up an Object[] copy, try to cast it to Integer[], and then do it correctly.

Java
import java.util.HashSet;
import java.util.Set;

public class HashSetToArrayObjects {
    public static void main(String[] args) {
        Set<Integer> scores = new HashSet<>();
        scores.add(70);
        scores.add(85);
        scores.add(90);

        Object[] items = scores.toArray();
        int total = 0;
        for (Object item : items) {
            total += (Integer) item;
        }
        System.out.println("length: " + items.length + ", total: " + total);

        try {
            Integer[] typed = (Integer[]) scores.toArray();
            System.out.println("cast worked: " + typed.length);
        } catch (ClassCastException e) {
            System.out.println("(Integer[]) cast -> ClassCastException");
        }

        Integer[] right = scores.toArray(new Integer[0]);
        System.out.println("toArray(new Integer[0]) length: " + right.length);
    }
}

How It Works

  1. Elements need a cast. Each item of the Object[] is cast to Integer before it is added to the total of 70 + 85 + 90 = 245.
  2. The array itself cannot be cast. The no-argument form builds an array whose real type is Object[], and Java refuses to treat it as Integer[] at run time.
  3. The compiler cannot see it. The cast is legal syntax, so the failure only shows up when the line executes, inside the try block.
  4. The typed form works. Passing new Integer[0] makes toArray create a real Integer[] of length 3.

Example 3 — A Bigger Array Gets a null Marker

Pass an array with spare room, then one that is too small, and see which array comes back.

Java
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class HashSetToArrayBigger {
    public static void main(String[] args) {
        Set<String> letters = new HashSet<>();
        letters.add("x");
        letters.add("y");

        String[] slots = new String[4];
        Arrays.fill(slots, "-");

        String[] result = letters.toArray(slots);
        System.out.println("same array: " + (result == slots));
        System.out.println("slots: " + Arrays.toString(slots));

        String[] small = new String[1];
        String[] other = letters.toArray(small);
        System.out.println("small reused: " + (other == small) + ", length " + other.length);
    }
}

How It Works

  1. Room to spare. slots has four places for two letters, so toArray fills the array you passed and returns that same object.
  2. The marker. The first two places hold the elements, the third (right after the last element) is set to null, and the fourth keeps its old "-".
  3. Too small. small has one place for two letters, so toArray allocates a new String[] of length 2 instead.
  4. Use the return value. Always read the result rather than the array you passed, because it may be a different array.

Frequently Asked Questions

Call set.toArray(new String[0]) for a String[] (use the right type for your elements), or set.toArray() for an Object[].
The no-argument toArray() creates an Object[]. To get a String[], pass an array: set.toArray(new String[0]).
Neither. It follows the iteration order of the set, which is hash order. Sort the array with Arrays.sort() if you need order.
No. toArray() copies the references into a new array, so adding to the array or the set does not affect the other. The element objects themselves are shared.
Both give a String[] with the elements. The first lets the method allocate the array; the second reuses your array because it is exactly the right size. Either is fine.

Back to the method index

See all 17 HashSet method guides grouped by what they do.

Method index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

14 people found this page helpful