Java Generics for Upper bound & lower bound wild cards

那年仲夏 提交于 2019-12-21 09:25:18

问题


I was reading java generics, I came across an interesting query. My question is as follows.

  1. 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
        }
    }
    
  2. 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
        }
    }
    

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

Can anyone please help me to understand this?


回答1:


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?




回答2:


actually, fortunately the same scenario, I got the answer under next pages of Sun Oracle documentation. please find the link below. may be useful to someone who would be searching in future.

Wildcard Capture



来源:https://stackoverflow.com/questions/16189229/java-generics-for-upper-bound-lower-bound-wild-cards

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!