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

The Diamond Operator: Type Inference

Using <> for cleaner instantiation: ArrayList<String> list = new ArrayList<>();

The Diamond Operator: Type Inference

What you'll learn: How to use the diamond operator (<>) to write cleaner, less repetitive generic instantiations.

When you create an instance of a generic class like ArrayList, you've already learned to specify the type argument on both sides of the declaration:

ArrayList<String> list = new ArrayList<String>();

Notice how String appears twice? Java can actually infer the type on the right side from the left side's declaration. That's where the diamond operator (<>) comes in—it lets you omit the redundant type argument:

ArrayList<String> list = new ArrayList<>();

The compiler sees ArrayList<String> on the left and automatically fills in the <> on the right with String. You get the same type safety without the repetition.

Why It's Called the "Diamond"

The <> symbol looks like a diamond shape, hence the name. It was introduced in Java 7 to reduce boilerplate when instantiating generic types.

Works with Any Generic Type

This isn't just for ArrayList. You can use the diamond operator whenever you instantiate a generic class:

ArrayList<Integer> numbers = new ArrayList<>();
ArrayList<Double> prices = new ArrayList<>();

Type Inference in Action

The diamond operator relies on type inference—the compiler deduces what type you meant based on context. The left-hand declaration provides that context, so the right-hand side doesn't need to repeat it.

Think of it like ordering food: "I'll have a large pepperoni pizza" followed by "and a large too" (pointing at something else). The "large" is inferred from context—you don't need to repeat the full description.

Key Takeaway: The diamond operator (<>) lets Java infer the type argument during instantiation, making your code cleaner while preserving full type safety: ArrayList<String> list = new ArrayList<>();