9

我正在阅读 java 泛型,我遇到了一个有趣的查询。我的问题如下。

  1. 对于上限通配符

    public static void printList(List<? extends Number> list) {
        for (int i = 0; i < 10; i++) {
            list.add(i);// gives compilation error
        }
    }
    
  2. 对于下界通配符

    public static void printList(List<? super Integer> list) {
        for (int i = 0; i < 10; i++) {
            list.add(i);// successfully compiles
        }
    }
    

我对此感到困惑,因为查看 Sun Oracle 文档我了解代码也应该针对第 1 点进行编译

上限通配符 下限通配符

谁能帮我理解这一点?

4

2 回答 2

10

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>();

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?

于 2013-04-24T10:40:20.510 回答
2

实际上,幸运的是,同样的情况,我在 Sun Oracle 文档的下一页中得到了答案。请找到下面的链接。可能对将来要搜索的人有用。

通配符捕获

于 2013-04-24T10:28:19.810 回答