Constructor Type Inference
What you'll learn: How Java automatically determines generic type arguments when you create objects using constructors.
The Core Idea
When you instantiate a generic class, Java doesn't always need you to spell out the type arguments explicitly. The compiler can infer them from two sources: the types of arguments you pass to the constructor, and the type of the variable you're assigning to. This makes your code cleaner and less repetitive.
From Constructor Parameters
If you pass arguments to a constructor, Java examines their types to deduce the type parameters:
// The constructor receives a String, so T is inferred as String
Box<String> box1 = new Box<>("Hello");
// The argument is an Integer, so T becomes Integer
Box<Integer> box2 = new Box<>(42);
From Assignment Context
Even without constructor arguments, Java looks at the left side of the assignment:
// Java sees you're assigning to Box<Double>, so it infers T = Double
Box<Double> box3 = new Box<>();
// Works with multiple type parameters too
Pair<String, Integer> pair = new Pair<>(); // both types inferred
The Diamond Operator's Role
The diamond operator (<>) tells Java: "figure out the types yourself." Without it, you'd need to repeat the type arguments on both sides, which feels redundant.
Think of It Like a Puzzle
The compiler acts like a detective: it examines all available clues (constructor arguments, variable type) and solves for the missing type parameters. You provide the hints; Java fills in the blanks.
Key Takeaway:
Constructor type inference lets Java deduce generic type arguments from constructor parameters and the assignment target type, eliminating redundant type specifications when using the diamond operator.