我正在阅读java泛型,我遇到了一个有趣的查询。我的问题如下。
I was reading java generics, I came across an interesting query. My question is as follows.
对于上限通配符
For an upper bounded wildcard public static void printList(List<? extends Number> list) { for (int i = 0; i < 10; i++) { list.add(i);// gives compilation error } }
对于下界通配符
For a lower bounded wildcard
public static void printList(List<? super Integer> list) { for (int i = 0; i < 10; i++) { list.add(i);// successfully compiles } }
我对此感到困惑,因为查看Sun Oracle文档我理解代码应该编译为点1以及
I am confused with this because looking at the Sun Oracle documentation I understand that the code should compile for point 1 as well
上限通配符 下限通配符<
Upper Bound Wildcard Lower Bound Wildcard
推荐答案
任何人都可以帮我理解吗? >这是因为当你使用上限时,你不能向集合添加元素,只能读取它们。
This is because when you are using upper bound, you cannot add elements to collection, only read them.
这意味着这些是一些法律赋值:
this means that these are some of legal assignments:
List<? extends Number> l = new ArrayList<Integer>(); List<? extends Number> l = new ArrayList<Double>();,所以你不能保证当添加对象时,它将保存正确类型的对象。为了更好的解释,请按照: 如何我添加到List< ;? extends Number>数据结构?
so you cannot guarantee that when adding object, it will hold correct types of objects. for better explatation please follow: How can I add to List<? extends Number> data structures?