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.
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
Parameter
Description
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 Value
Description
Object[] / T[]
An array holding all elements of the set in sorted ascending order.
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.
Trailing null marker. Slot 2 (right after 101 and 205) is overwritten with null, while slot 3 keeps its old value 9.
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.