Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

generics wildcard

 
ming ming
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
in the following code what can we add ?
 
babu sharath
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If there is wild card , We can not add any thing .
( unless it is super .. Ex: ? extends super )
 
babu sharath
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry ... In previous reply example was wrong...
It is like .. ( ? super Number )
than we can add .
 
Vijay Raj
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let's take into consideration, the following class hierarchy.


When we say, ? extends A, it means that both B and A can also be taken into consideration. Now if we have,


and, say, add() was possible, then we would be able to add an element of type C also. Just to dis-allow this, its a compile time error.

regards,
vijay.
 
Gowher Naik
Ranch Hand
Posts: 643
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check code below


import java.util.*;
public class Test {
public static void main (String args []) {
List<Number>x=new ArrayList<Number>();
x.add(new Integer("10"));
take(x);
take1(x);
}
public static void take(List<? extends Number>x){
//In this method nothing can be added to List x
//This method becomes read only method
System.out.println(x.get(0));
}
public static void take1(List<? super Number>x){
//In this method anything extends Number can
//be added to List x
x.add(new Integer("20"));
x.add(new Long("20"));
x.add(new Float("20.120"));
for(Object n:x){
System.out.println(n);
}
}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic