Course contentsShow
← Java
Lesson 1500 of 2,87033. Streams API: Terminal OperationsFree lesson

Common Pitfalls with toArray(Object[]::new)

Avoid casting errors by understanding when Object[]::new is incorrect for generic types.

Common Pitfalls with toArray(Object[]::new)

You'll learn why using Object[]::new as your array generator can lead to casting errors with generic types.

The Problem with Object[]::new

When you call stream.toArray(Object[]::new), you're explicitly requesting an Object[] array. This seems harmless, but it creates a dangerous trap: you cannot cast an Object[] to a more specific array type like String[] or Integer[].

Here's what goes wrong:

List<String> names = List.of("Alice", "Bob", "Charlie");

// This compiles but throws ClassCastException at runtime!
String[] array = (String[]) names.stream()
                                  .toArray(Object[]::new);

The stream does contain String objects, but the array itself was created as Object[]. Java arrays are covariant for reading but reified at runtime—meaning the array "knows" it's an Object[] and refuses to be treated as a String[].

The Correct Solution

Always use the correct array type constructor:

// Correct: creates an actual String[] array
String[] array = names.stream()
                      .toArray(String[]::new);

Think of it like ordering a container: Object[]::new orders a generic "object box," while String[]::new orders a "string box." You can't just relabel the generic box afterward—the box itself has a fixed type.

Why This Matters

This pitfall typically occurs when developers try to be "generic" or copy-paste code without understanding the array generator's purpose. The IntFunction<A[]> parameter exists specifically so the stream can create the correct array type, not just any array.

Key Takeaway:
Never use Object[]::new when you need a typed array—always match the array constructor to your stream's element type to avoid ClassCastException.