Alex Rivera | Logout

What is the point of the diamond operator (<>) in Java?

Asked 2010-11-12T16:43:23.820
511

The diamond operator in java 7 allows code like the following:

List<String> list = new LinkedList<>();

However in Java 5/6, I can simply write:

List<String> list = new LinkedList();

My understanding of type erasure is that these are exactly the same. (The generic gets removed at runtime anyway).

Why bother with the diamond at all? What new functionality / type safety does it allow? If it doesn't yield any new functionality why do they mention it as a feature? Is my understanding of this concept flawed?

Edit
Report

1 Answer

8

When you write List<String> list = new LinkedList();, the compiler produces an "unchecked" warning. You may ignore it, but if you got used to ignoring these warnings, you may also miss a warning that notifies you about a real type-safety problem.

So, it's better to write code that doesn't generate extra warnings, and the diamond operator allows you to do it in a convenient way without unnecessary repetition.

answered 2010-11-12T16:53:57.753

Your Answer