• 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
  • Tim Cooke
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Henry Wong
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Mikalai Zaikin
  • Himai Minh

generics

 
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This qs is from generics topic seltest from k& B ? can any one explain this code
Assume that Parent is a Base class and Child is a Derived class

List<? super Parent> alList = new ArrayList<Child>(); //line 1
List<?> alList = new ArrayList< ? super Child>(); //line 2
List<?> alList = new ArrayList<? extends Parent>(); //line 3
List<? extends Child> alList = new ArrayList<Parent>(); //line 4
List<?> alList = new ArrayList<Parent>(); //line 5

a)only 1

b)only 4

c)only 5

d)2 and 3

e)1 and 4
 
Ranch Hand
Posts: 169
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


line 2 and line 3 are wrong because '?' cannot be used with new.

line 1 is wrong because it says::
List<? super Parent> alList = new ArrayList<Child>();
i.e any thing which is a super class of Parent including Parent..
since Child class is a sub-class hence line 1 is wrong..

List<? extends Child> alList = new ArrayList<Parent>();//line 4
this is wrong because it says "anything which is a sub-class of Child(including Child)..and since Parent is a Super Class hence it is also wrong..

line 5 is correct
List<?> alList = new ArrayList<Parent>();
because it says "List<?>" which means anything...it can be a Child or Parent or Integer or Object or Cat or Dog !!
reply
    Bookmark Topic Watch Topic
  • New Topic