Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics for Upper bound & lower bound wild cards

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?

like image 215
chaosguru Avatar asked Apr 24 '13 10:04

chaosguru


1 Answers

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?

like image 112
Filip Zymek Avatar answered Oct 07 '22 01:10

Filip Zymek