简体   繁体   English

Java中的下界通配符

[英]Lower bounded wildcards in java

Consider the following example, 考虑以下示例,

List<? super Number> list1 = new ArrayList<>();
list1.add(10);
list1.add(10.10);
list1.add(20.20d);

and another list to which i assign list1 和我分配给list1的另一个列表

List<? super Integer> list = list1;
System.out.println(list.toString());

Now, when i print the list it contains double values also BUT the list is only supposed to hold Integer and anything above Integer . 现在,当我打印列表时,它也包含双精度值, 但该列表仅应容纳Integer以及Integer以上的任何内容

If the above is fine then shouldn't the following compile as well ? 如果以上方法都可以,那么下面的代码是否也应该编译?

list.add(30.30);

Everything makes sense if you consider the possible things you could assign to it. 如果您考虑可以分配给它的可能事物,那么一切都有意义。

List<? super Number> list1 = new ArrayList<Object>(); // works
List<? super Number> list1 = new ArrayList<Number>(); // works
List<? super Number> list1 = new ArrayList<Integer>(); // doesn't work

Anything that works on the right hand side will accept a Double . 任何在右侧起作用的东西都将接受Double

List<? super Integer> list = new ArrayList<Object>(); // works
List<? super Integer> list = new ArrayList<Number>(); // works
List<? super Integer> list = new ArrayList<Integer>(); // works

Anything that you could assign to list1 you could also assign to list . 您可以分配给list1所有内容也可以分配给list So list = list1 works just fine. 所以list = list1可以正常工作。 But not all of the things you could assign to list will accept a Double , so it doesn't compile. 但是, 并非您可以分配给list都接受Double ,因此它不会编译。

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

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