Generic Constructor References
What you'll learn: How to use constructor references when the class or method involves generic type parameters.
The Core Idea
When working with generic classes (like List<T>, Optional<T>, or your own generic types), constructor references can automatically infer the type parameters from context—just like lambdas do. This means you can create instances of generic classes cleanly without explicitly specifying angle brackets every time.
How It Works
The target type determines what generic parameters to use. If you're supplying a Supplier<List<String>>, Java knows the constructor reference ArrayList::new should create an ArrayList<String>.
// Context provides the type: Supplier<List<String>>
Supplier<List<String>> listSupplier = ArrayList::new;
List<String> names = listSupplier.get(); // Empty ArrayList<String>
// With Function: String as input, ArrayList<String> as output
Function<Integer, List<String>> listMaker = ArrayList::new;
List<String> list = listMaker.apply(10); // ArrayList with initial capacity 10
Generic Methods
When a generic method expects a constructor reference, the type flows through seamlessly:
public static <T> List<T> createList(Supplier<List<T>> constructor) {
return constructor.get();
}
// Type inference determines T = Integer
List<Integer> numbers = createList(ArrayList::new);
The method's type parameter T is inferred from usage, and the constructor reference adapts accordingly.
Why This Matters
Without this feature, you'd need verbose lambda expressions that explicitly instantiate generic classes. Constructor references keep your code concise while maintaining full type safety through Java's type inference system.
Key Takeaway: Generic constructor references automatically infer type parameters from the target functional interface type, allowing you to instantiate generic classes cleanly and safely without explicit type arguments.