Java don't allow putting multiple subtype of a superType into a list if <? extends superType> is the declared generic type of the list. Because in this case lists are treated as read only to enforce it contains only objects of it's dynamic type.
Line commented by //1 going to return the compile error.
My question is:
- why would line commented by //2 compiles? It eventually puts multiple subType objects into the list.
- in case it's not a problem here then why throw a compile error at //1
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class Scratch {
static class Animal {}
static class Dog extends Animal {}
static class Cat extends Animal {}
public static void main(String[] args) {
List<Cat> cats = new ArrayList<>();
List<Dog> dogs = new ArrayList<>();
//List<? extends Animal> animalsOfTwoTypes = new ArrayList<Dog>();
//animalsOfTwoTypes.add(new Dog()); //1
List<? extends Animal> animals = Stream.of(cats, dogs) //2
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
}