Java Generics for high end and low level wild cards

I read java generics, I came across an interesting query. My question is the following.

  • For upper restricted wildcard

    public static void printList(List<? extends Number> list) { for (int i = 0; i < 10; i++) { list.add(i);// gives compilation error } } 
  • For 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 by this because, looking at the Sun Oracle documentation, I understand that the code must also compile for point 1

Upper Bounding Mark Lower Substitution Binding

Can anyone help me figure this out?

+7
source share
2 answers

This is because when you use the top border, you cannot add items to the collection, but only read them.

this means that these are some of the tasks:

 List<? extends Number> l = new ArrayList<Integer>(); List<? extends Number> l = new ArrayList<Double>(); 

therefore, you cannot guarantee that when you add an object, it will contain the correct types of objects. for a better explanation, please follow: How to add to the list <? extends number> data structures?

+7
source

Actually, fortunately, the same scenario, I got the answer on the following pages of Sun Oracle documentation. Please find the link below. may be useful for those who will seek in the future.

Wildcard file

+1
source

All Articles