Array Constructor References
What you'll learn: How to use a special method reference syntax to create arrays dynamically, especially useful with streams and collections.
What Are Array Constructor References?
Just as you can reference constructors for objects using ClassName::new, Java provides a special syntax for creating arrays: Type[]::new. This tells Java "give me a constructor that creates an array of this type."
Think of it like ordering a custom-sized container: you don't specify the size upfront—you provide a blueprint that says "when you know how many items you have, make an array of that size for me."
The Syntax
The syntax follows a simple pattern:
Type[]::new
For example:
String[]::new— creates a String array constructorInteger[]::new— creates an Integer array constructorPerson[]::new— creates a Person array constructor
This reference is actually an IntFunction<Type[]> — it takes an integer (the size) and returns an array of that size.
Common Use Case: Stream.toArray
The most common place you'll use array constructor references is with Stream.toArray():
List<String> names = List.of("Alice", "Bob", "Charlie");
// Without array constructor reference (returns Object[])
Object[] objArray = names.stream().toArray();
// With array constructor reference (returns String[])
String[] stringArray = names.stream().toArray(String[]::new);
The String[]::new tells toArray exactly what type of array to create, sized to fit all the stream elements.
Key Takeaway: Use Type[]::new as a concise, type-safe way to create arrays dynamically, commonly with Stream.toArray() to avoid getting an Object[] array.