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

后端 未结 7 2374
渐次进展
渐次进展 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:05

    All said in the other responses are valid but the use cases are not completely valid IMHO. If one checks out Guava and especially the collections related stuff, the same has been done with static methods. E.g. Lists.newArrayList() which allows you to write

    List names = Lists.newArrayList();
    

    or with static import

    import static com.google.common.collect.Lists.*;
    ...
    List names = newArrayList();
    List names = newArrayList("one", "two", "three");
    

    Guava has other very powerful features like this and I actually can't think of much uses for the <>.

    It would have been more useful if they went for making the diamond operator behavior the default, that is, the type is inferenced from the left side of the expression or if the type of the left side was inferenced from the right side. The latter is what happens in Scala.

提交回复
热议问题