Java TreeSet toArray() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
TreeSet

Definition

In Java, toArray() copies all elements of a TreeSet into an array in ascending sorted order. The zero-argument overload returns an Object[].

Pass an empty typed array like set.toArray(new String[0]) to get back a strongly typed String[] directly, with no casts required when reading elements.

An instance method of java.util.TreeSet (Java 1.2+): a red-black tree NavigableSet backed by a TreeMap that keeps unique elements sorted in O(log n) time and is not thread-safe. Inherited from AbstractCollection (since Java 1.2). Java 11 also added toArray(IntFunction) on Collection, while the examples here use Java 8-compatible toArray(new T[0]).

Syntax

Use toArray() for Object[], or pass new Type[0] for a typed array.

Java
TreeSet<String> tags = new TreeSet<>(Arrays.asList("java", "api", "tree"));
Object[] raw = tags.toArray();                    // Object[]
String[] typed = tags.toArray(new String[0]);     // String[] -> [api, java, tree]
CallWhat it does
set.toArray()Returns a new Object[] in sorted order.
set.toArray(new String[0])Returns a properly typed String[] sized to match.
Arrays.toString(arr)Formats the array contents cleanly for printing.
arr[0] = ...Modifies only the array; the TreeSet is untouched.

Notice toArray() and toArray(T[] a) are inherited from AbstractCollection rather than overridden on TreeSet, using TreeSet's ascending iterator under the hood.

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

// Declared in Collection<E> (Java 11+)
default <T> T[] toArray(IntFunction<T[]> generator)

Parameters

ParameterDescription
a (T[])Typed overload only: array into which elements are stored if large enough; otherwise determines the runtime type of the newly allocated array.

Return Value

Return ValueDescription
Object[] / T[]An array holding all elements of the set in sorted ascending order.

Compare with Similar Methods

Converting or copying a TreeSet:

MethodHow it differs
clone()Creates another TreeSet instead of an array.
iterator()Walks sorted elements one by one without copying into an array.
ArraysProvides Arrays.toString() and Arrays.asList() to go back and forth.
ArrayList.toArray()Same contract, copying list elements in index order.

Java Examples

Example 1 — Copy Sorted Tags Into a String[] With new String[0]

Convert a TreeSet<String> into a String[], print it with Arrays.toString(), and mutate the array without affecting the set.

Java
import java.util.Arrays;
import java.util.TreeSet;

public class TreeSetToArrayStrings {
    public static void main(String[] args) {
        TreeSet<String> tags = new TreeSet<>(Arrays.asList("sorting", "java", "collections"));

        String[] arr = tags.toArray(new String[0]);
        System.out.println("array (" + arr.length + "): " + Arrays.toString(arr));

        arr[0] = "algorithms";
        System.out.println("edited array: " + Arrays.toString(arr));
        System.out.println("set intact:   " + tags);
    }
}

How It Works

  1. Sorted array copy. Passing new String[0] allocates a String[] of length 3 in ascending alphabetical order.
  2. Readable output. Wrapping in Arrays.toString(arr) displays [collections, java, sorting] rather than a raw class tag.
  3. Independent array. Overwriting arr[0] changes only the array while tags stays untouched.

Example 2 — Compare toArray() (Object[]) vs Typed Integer[]

See why toArray() requires element casts while toArray(new Integer[0]) lets loops unbox cleanly.

Java
import java.util.Arrays;
import java.util.TreeSet;

public class TreeSetToArrayTypes {
    public static void main(String[] args) {
        TreeSet<Integer> scores = new TreeSet<>(Arrays.asList(30, 10, 20));

        Object[] objs = scores.toArray();
        System.out.println("raw component type: " + objs.getClass().getComponentType().getSimpleName());
        int first = (Integer) objs[0];

        Integer[] typed = scores.toArray(new Integer[0]);
        int sum = 0;
        for (int n : typed) {
            sum += n;
        }
        System.out.println("first=" + first + ", typed sum=" + sum);
    }
}

How It Works

  1. Object[] needs casts. Zero-argument toArray() always produces an Object[], so reading objs[0] as an Integer needs an explicit cast.
  2. Typed array avoids casts. toArray(new Integer[0]) returns an Integer[] that enhanced for loops unbox straight to int.
  3. Ascending order preserved. objs[0] holds 10 and the three sorted elements sum to 60.

Example 3 — Oversized Arrays Insert a null Marker; Wrong Types Throw

Pass an oversized target array to observe the null terminator at index size(), then trigger ArrayStoreException.

Java
import java.util.Arrays;
import java.util.TreeSet;

public class TreeSetToArrayEdge {
    public static void main(String[] args) {
        TreeSet<Integer> ids = new TreeSet<>(Arrays.asList(101, 205));

        Integer[] big = {9, 9, 9, 9};
        Integer[] res = ids.toArray(big);
        System.out.println("reused same array? " + (res == big));
        System.out.println("oversized contents: " + Arrays.toString(big));

        try {
            ids.toArray(new String[0]);
        } catch (ArrayStoreException e) {
            System.out.println("wrong array type: " + e.getClass().getSimpleName());
        }
    }
}

How It Works

  1. Target array reused when large enough. Because big had 4 slots and ids had 2 items, Java filled big in place and returned the same array reference.
  2. Trailing null marker. Slot 2 (right after 101 and 205) is overwritten with null, while slot 3 keeps its old value 9.
  3. Incompatible array type fails. Copying Integer elements into a String[] immediately throws ArrayStoreException.

Frequently Asked Questions

Call set.toArray(new String[0]), which returns a String[] holding the elements in ascending sorted order. On Java 11+, set.toArray(String[]::new) also works.
Due to Java generic type erasure, a TreeSet does not know its runtime element type without an array prototype. Passing new String[0] tells it which array type to allocate.
Both work. Passing new String[0] is concise, avoids sizing bugs, and is equally fast or faster on modern JVMs.
Yes. toArray() iterates the TreeSet in ascending order, so the array preserves the TreeSet sorted order.
No. The array is a separate copy of the element references, though mutable element objects themselves remain shared.

Back to the method index

See all 25 TreeSet 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.

13 people found this page helpful