Course contentsShow
← Java
Lesson 875 of 2,87021. Generics FundamentalsFree lesson

The Diamond Operator (<>)

Master type inference with the diamond operator introduced in Java 7 to simplify generic instantiation.

The Diamond Operator (<>)

You'll learn how Java 7's diamond operator simplifies generic instantiation through type inference.

The Redundancy Problem

Before Java 7, creating generic objects required repeating type arguments on both sides of the assignment:

List<String> names = new ArrayList<String>();
Map<Integer, String> idMap = new HashMap<Integer, String>();

Notice how String and Integer, String appear twice? The compiler already knows the required types from the left side—so why repeat them?

The Diamond Solution

Java 7 introduced the diamond operator (<>) to eliminate this redundancy. The compiler infers the type arguments from the variable declaration:

List<String> names = new ArrayList<>();
Map<Integer, String> idMap = new HashMap<>();

The empty angle brackets tell the compiler: "Use the type parameters you already know."

How Type Inference Works

Think of it like ordering food: if you say "I want a large pepperoni pizza" and then call out "bring me that pizza," everyone knows which pizza you mean. Similarly, when you declare List<String>, the compiler remembers you need String when it sees new ArrayList<>().

When to Use It

Use the diamond operator whenever you instantiate a generic class and the type arguments can be inferred from context:

// Clear and concise
Box<Integer> box = new Box<>();

// Works with multiple type parameters
Pair<String, Double> pair = new Pair<>();

The diamond operator only works on the right side of an assignment or where types can be inferred—you still need full type arguments on the left side declaration.

Key Takeaway: The diamond operator (<>) eliminates redundant type arguments during generic instantiation by letting the compiler infer types from context, making your code cleaner and more maintainable.