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

前端 未结 3 2018
南旧
南旧 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:07

    First of all: unless you're using Java 7 all of this will not work, because the diamond <> has only been introduced in that Java version.

    Also, this answer assumes that the reader understands the basics of generics. If you don't, then read the other parts of the tutorial and come back when you understand those.

    The diamond is actually a shortcut for not having to repeat the generic type information when the compiler could find out the type on its own.

    The most common use case is when a variable is defined in the same line it's initialized:

    List list = new ArrayList<>(); // is a shortcut for
    List list = new ArrayList();
    

    In this example the difference isn't major, but once you get to Map>>> it'll be a major enhancement (note: I don't encourage actually using such constructs!).

    The problem is that the rules only go that far. In the example above it's pretty obvious what type should be used and both the compiler and the developer agree.

    On this line:

    list.addAll(new ArrayList<>());
    

    it seems to be obvious. At least the developer knows that the type should be String.

    However, looking at the definition of Collection.addAll() we see the parameter type to be Collection.

    It means that addAll accepts any collection that contains objects of any unknown type that extends the type of our list. That's good because it means you can addAll a List to a List, but it makes our type inference trickier.

    In fact it makes the type-inference not work within the rules currently laid out by the JLS. In some situations it could be argued that the rules could be extended to work, but the current rules imply don't do it.

提交回复
热议问题