Video in progress

Strong Middle 🌊 Streams and lambdas

What is the difference between stream.toArray() and toArray(String[]::new), and why does (String[]) stream.toArray() throw a ClassCastException?

toArray() with no arguments always returns an Object[]: even if it contains Strings, the array's type is Object[], and it can't be cast to String[]. For an array of the right type you pass a generator: toArray(String[]::new).

📖 Answer

String[] a = (String[]) names.stream().toArray();     // ClassCastException
String[] b = names.stream().toArray(String[]::new);   // right

In Java an array knows its own type at runtime. Generics are erased, so a Stream<T> doesn't know which T it is and can't create new T[n]. The generator, an IntFunction<A[]>, supplies that information: String[]::new is really n -> new String[n].

There's also the reverse mistake, when the generator doesn't fit the elements:

Object[] objs = Stream.of("a", 1, 2.0).toArray(String[]::new);   // ArrayStoreException

The compiler doesn't catch this; the error appears only at runtime.

The same goes for collections: the old list.toArray(new String[0]) and, since Java 11, list.toArray(String[]::new). Yes, new String[0] is no slower than new String[list.size()], and often even faster; on modern JVMs passing an empty array is the recommended form.

For primitives you don't need a generator: IntStream.toArray() gives an int[] right away.

int[] ids = users.stream().mapToInt(User::id).toArray();

When you need an array: passing to varargs methods, legacy APIs or String.join. Elsewhere I prefer working with a List: array covariance is exactly the source of unexpected errors like the ArrayStoreException above.