• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

generics wildcard

 
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
in the following code what can we add ?
 
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sorry ... In previous reply example was wrong...
It is like .. ( ? super Number )
than we can add .
 
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 643
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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);
}
}
}
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic