Consider
class MyClass{
List<? extends Number> nums= new ArrayList<Integer>();
nums.add(3.14);//Compile error
}
In the error's description we have: excepted add(int, Object), found add(int,CAP#1)
. What's defenition of CAP#1
? Why this error caused?
This is because nums is a List<? extends Number>
List<? extends Number>
, so the compiler knows that it is a List of Number or some subclass of Number, but it does not know which. Therefore, you will never be allowed to add anything to such a list. Here's an example of what this means:
List<? extends Number> nums= new ArrayList<Integer>();
and
List<? extends Number> nums= new ArrayList<Double>();
are both valid assignments. However, if you do:
nums.add(new Integer(4));
the compiler will not accept this as it cannot be certain that nums is a List of Integer
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.