• 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

Regarding generics

 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
One question from javabeat.net

public static <T> void addandDisp(Collection<T> cs, T t)
{
for (T o : cs)
{
s.add(o);
}
for (T o : cs)
{
System.out.println(o);
}
}

//call 1
List<? super Object> ls1 = new LinkedList<Object>();
addandDisp(ls1,new String());

//call 2
List<? extends Object> ls2 = new LinkedList<Object>();
addandDisp(ls2,new Object());

//call 3
List<Object> ls3 = new LinkedList<Object>();
addandDisp(ls3,new String());

//call 4
List<? super Object> ls4 = new LinkedList<Object>();
addandDisp(ls4,new Object());

Which call(s) to above method(addandDisp) are error free?

a)only 3

b)only 1 and 3

c)only 1 and 4

d)only 1,2 and 3

e)only 1,3 and 4

Answer e)

(call 2)Method call 2 cannot work,because the compiler cannot gurantee
the type to substitute.But in all other calls it is guranteed.

My doubt is how we can add String in call1.
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Because in that case declaring the type in the List to be ? super Object, means Object or a superclass of Object.

Since there is no superclass of Object, the only type that can be in the List is Object.
 
Rajeswari Kumar
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanku. Sometimes iam really get confused
 
reply
    Bookmark Topic Watch Topic
  • New Topic