Why doesn't the diamond operator work within a addAll() call in Java 7?

前端 未结 3 2027
南旧
南旧 2021-01-17 14:13

Given this example from the generics tutorial.

List list = new ArrayList<>();
list.add(\"A\");

// The following statement should fail si         


        
3条回答
  •  醉酒成梦
    2021-01-17 15:08

    The explanation from the Type Inference documentation seems to answer this question directly ( unless I'm missing something else ).

    Java SE 7 and later support limited type inference for generic instance creation; you can only use type inference if the parameterized type of the constructor is obvious from the context. For example, the following example does not compile:

    List list = new ArrayList<>();
    list.add("A");
    
      // The following statement should fail since addAll expects
      // Collection
    
    list.addAll(new ArrayList<>());
    

    Note that the diamond often works in method calls; however, for greater clarity, it is suggested that you use the diamond primarily to initialize a variable where it is declared.

    In comparison, the following example compiles:

    // The following statements compile:
    
    List list2 = new ArrayList<>();
    list.addAll(list2);
    

提交回复
热议问题