Why can't diamond infer types on anonymous inner classes?

后端 未结 3 1204
别那么骄傲
别那么骄傲 2020-12-28 16:53

In Java 7 and later, diamond can be used to infer types on normally like so without an issue:

List list = new ArrayList<>();
3条回答
  •  灰色年华
    2020-12-28 17:29

    In short, the <> does little to infer types, it turns off the warning you would get without it.

    EDIT: As @Natix points out it does some checking.

    List ints = new ArrayList<>();
    List copy = new ArrayList<>(ints);
    

    produces a compilation error

    Error:Error:line (42)error: incompatible types
    required: List
    found:    ArrayList
    

    As you can see the <> is taking the type of the argument, not inferring the type from the type of copy

提交回复
热议问题