简体   繁体   English

通配符捕获/泛型

[英]Wildcard captures/Generics

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) . 在错误的描述中我们有: excepted add(int, Object), found add(int,CAP#1) What's defenition of CAP#1 ? CAP#1什么? Why this error caused? 为什么会出现此错误?

This is because nums is a List<? extends Number> 这是因为nums是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. List<? extends Number> ,因此编译器知道它是Number of Number或Number的某个子类,但它不知道哪个。 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 . 编译器不会接受这个,因为它不能确定nums是一个Integer列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM