问题
I am using the below code and tryin to add CHild object is the list:
List<? extends Parent> list = new ArrayList<Child>();
list.add(new Child()); //error: The method add(capture#1-of ? extends Parent) in the type List<capture#1-of ? extends Parent> is not applicable for the arguments (Child)
class Parent{
}
class Child extends Parent{
}
I want to know why compiler throws error here?
回答1:
If you go through the Generic Guidelines stated by Oracle docs, these kind of list declarations are tend to be read-only (no write operations can be performed)
Quoted from the page
A list defined by
List<? extends ...>
can be informally thought of as read-only, but that is not a strict guarantee.
As per your example, let us assume Child2
and Child3
extends Parent
, then
List<? extends Parent>
list can be a list of any of these subclasses. Adding a specific subclass element can cause runtime error, thus compiler complains in advance
回答2:
As per your example, i am able to figure out that List of Parent and List of Child are not subtype of each other even though Child is subtype of Parent, in a similar way like List of Number and List of Integer are not subtype of either. If it was possible, you could have added not an Integer to List of Number which lead to type safety voilation.
For your requirement you can do something like below mentioned
List<Number> numberList = new ArrayList<Number>();
List<Integer> integerList = new ArrayList<Integer>();
List<Double> doubleList = new ArrayList<Double>();
List<Float> floatList = new ArrayList<Float>();
numberList.addAll(integerList);
numberList.addAll(doubleList);
numberList.addAll(floatList);
Here check for arguments to addAll() method.
来源:https://stackoverflow.com/questions/25619676/java-generic-type-for-wildcard-extends-allow-to-add-only-null