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

后端 未结 7 2346
渐次进展
渐次进展 2020-11-21 04:20

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

List list = new LinkedList<>();

However in Java 5/6, I c

相关标签:
7条回答
  • 2020-11-21 05:24

    Your understanding is slightly flawed. The diamond operator is a nice feature as you don't have to repeat yourself. It makes sense to define the type once when you declare the type but just doesn't make sense to define it again on the right side. The DRY principle.

    Now to explain all the fuzz about defining types. You are right that the type is removed at runtime but once you want to retrieve something out of a List with type definition you get it back as the type you've defined when declaring the list otherwise it would lose all specific features and have only the Object features except when you'd cast the retrieved object to it's original type which can sometimes be very tricky and result in a ClassCastException.

    Using List<String> list = new LinkedList() will get you rawtype warnings.

    0 讨论(0)
提交回复
热议问题