Explain Collection.toArray() and toArray(T[]). Why does the no-arg version return Object[], and what is the correct way to call the typed overload?
answer
- toArray() -> Object[] because of type erasure
- never cast toArray() to a typed array (ClassCastException)
- toArray(new String[0]): zero-length, no slower
- Java 11: toArray(String[]::new)
- oversized array -> null at index size
basics
~20 stoArray() returns an Object[] because the collection doesn't know its element type at runtime (type erasure). toArray(T[]) returns a properly typed array; a common call is list.toArray(new String[0]), and Java 11 added the cleaner list.toArray(String[]::new).
solid answer
~50 sCollection has three array-conversion methods. toArray() returns Object[] - it can't return String[] because generics are erased at runtime, so the collection has no record of its element type. toArray(T[] a) takes a typed array argument that supplies the runtime component type via reflection: if a is big enough the elements go into it (with room to spare, a[size] is set to null), otherwise a new array of the same type is allocated and returned. A common call is list.toArray(new String[0]): on HotSpot a zero-length array is no slower than a presized one, since C2 can skip zeroing the new result array. Since Java 11 you can write list.toArray(String[]::new), the clearest form, whose default implementation calls the generator with zero. A classic bug is casting toArray() to String[] - that throws ClassCastException because the actual runtime type is Object[]. Use a typed overload whenever you need a typed array.
code
java · 15 linesList<String> names = List.of("ann", "bob", "cy");
// 1. No-arg -> Object[]; casting it throws ClassCastException
Object[] objs = names.toArray();
// String[] bad = (String[]) names.toArray(); // RUNTIME ClassCastException
// 2. Typed overload, zero-length array (common before Java 11)
String[] a = names.toArray(new String[0]);
// 3. Java 11+ array-constructor reference (clearest)
String[] b = names.toArray(String[]::new);
// 4. Oversized array gets a null terminator at index size
String[] big = names.toArray(new String[5]);
// big -> [ann, bob, cy, null, null]; index 4 was never writtengo deeper
Knows toArray() gives Object[] and that toArray(new String[0]) gives a typed String array.
Explains type erasure as the reason for Object[], the fill-or-allocate behavior of toArray(T[]), and the ClassCastException pitfall of casting.
Discusses the zero-length-vs-presized performance nuance, the Java 11 toArray(IntFunction) overload, and the null-terminator edge case.
Connects this to reified arrays vs erased generics in the type system and chooses array vs Stream/Collection boundaries in public APIs to avoid leaking Object[].
## The array-conversion methods `Collection<E>` offers two classic ways to copy its contents into an **array**, plus a third since Java 11 (below): ```java Object[] toArray(); <T> T[] toArray(T[] a); ``` ## Why the no-arg version returns Object[] Java generics use **type erasure**: the type parameter `E` exists only at **compile time** and is *erased* at runtime. So at runtime a `List<String>` is just a `List` - the object has **no idea** its elements are `String`s. Because `toArray()` must build an array and the JVM needs a concrete **component type** to do so, the only type it can safely use is the universal supertype **`Object`**. Hence it returns **`Object[]`**, and the Javadoc makes that a contract: "The returned array's runtime component type is Object." This is why **casting the result fails**: ```java String[] bad = (String[]) list.toArray(); // ClassCastException at runtime ``` The runtime object really *is* an `Object[]`, and you cannot cast an `Object[]` down to `String[]` even if every element is a String - the array's own type is wrong. ## The typed overload toArray(T[] a) The second overload solves this by letting **you** supply an array of the desired type. The collection reads the **runtime component type** from `a` (via reflection: `a.getClass().getComponentType()`) and produces an array of that exact type: - If `a` is **large enough** (`a.length >= size`), the elements are stored into `a` and `a` itself is returned. With room to spare (`a.length > size`), the slot at index `size` is set to `null` (a sentinel), and any slots after it keep their old values. - If `a` is **too small**, a **new** array of the same runtime type and the right length is allocated and returned (your `a` is left untouched). So the *return value* (not necessarily your argument) is what you keep. ## How to call it correctly **Idiom 1 - zero-length array (common before Java 11, still fine):** ```java String[] arr = list.toArray(new String[0]); ``` Passing a **zero-length** array might look wasteful, but on HotSpot it is **no slower in practice** than a presized array (`new String[list.size()]`). On `ArrayList` a too-small array goes to `Arrays.copyOf`, a JIT intrinsic, and C2 can copy straight into the freshly allocated result without zeroing it first. A presized array was allocated and zeroed before `System.arraycopy` fills it. The presized version also risks a stale `null` if the collection shrinks between `size()` and `toArray`. **Idiom 2 - array constructor reference (Java 11+, clearest):** ```java String[] arr = list.toArray(String[]::new); ``` This `toArray(IntFunction<T[]>)` default method takes an array generator. Its default implementation calls the generator with **zero** and passes the result to `toArray(T[])`, so it does idiom 1's work with the zero out of sight. Most readable. Adding it also made `coll.toArray(null)` ambiguous, so since JDK 11 that line no longer compiles. `Collection`'s three methods read the same at JDK 25 and 27. **Streams alternative:** ```java String[] arr = list.stream().toArray(String[]::new); ``` ## The null-terminator gotcha If you (mistakenly) pass an **oversized** array, the element after the last copied one is set to `null`. Code that loops to `arr.length` instead of using the collection size can then hit an unexpected `null`. Passing a zero-length array sidesteps this entirely. ## Summary - `toArray()` -> `Object[]` because of erasure; **don't cast it**. - `toArray(T[])` -> typed array; supply the type via a zero-length array, or use the generator overload. - Prefer `toArray(String[]::new)` on Java 11+.
- Why does (String[]) list.toArray() throw ClassCastException even when every element is a String?The runtime object is literally an Object[], not a String[]. Array types are reified, so an Object[] cannot be cast to String[] regardless of its contents. Use toArray(new String[0]) instead.
- Is new String[0] or new String[list.size()] faster as the toArray argument?On HotSpot the zero-length array is no slower: on ArrayList it reaches Arrays.copyOf, and C2 can copy into the new array without zeroing it first, while a presized array is zeroed at allocation. It also avoids a stale null if the collection shrinks between size() and toArray.
- Casting (String[]) collection.toArray()
- Claiming a presized array is always faster than a zero-length one (on HotSpot the zero-length path is no slower)
- Forgetting the null-terminator when passing an oversized array
- Thinking toArray() can return a typed array if generics are 'smart enough' - erasure prevents it
- Collection.toArray(IntFunction)
- Java 11
Checked against JDK 27. toArray(IntFunction) exists since JDK 11, which is also when coll.toArray(null) stopped compiling; Collection's toArray methods read the same at JDK 25.
context
- Collection (Java SE 27 & JDK 27)docs.oracle.com
- Chapter 4. Types, Values, and Variablesdocs.oracle.com
- macroArrayCopy.cpp at jdk-27-gagithub.com