9

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?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
chaosguru
  • 1,933
  • 4
  • 30
  • 44
  • @baraky: thanks for the link I missed it somehow.. but still the question is why does it not compile when the Generic type knows that it has to be a class extended by Number. Sorry for redundant question. It is still unclear for me. – chaosguru Apr 24 '13 at 10:17

2 Answers2

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?

Community
  • 1
  • 1
Filip Zymek
  • 2,626
  • 4
  • 22
  • 31
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

chaosguru
  • 1,933
  • 4
  • 30
  • 44