• 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 K&B Mock exam question

 
Ranch Hand
Posts: 206
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,

I am a bit confused about the answer to the following question:

import java.util.*;
public class BackLister
{ // INSERT HERE
{
List<T> output = new LinkedList<T>();
for (T t : input) output.add(0, t);
return output;
}

}


Which of the following can be inserted at // INSERT HERE to compile and run

Correct Answer:
A. public static <T> List<T> backwards(List<T> input)
B. public static <T> List<T> backwards(List<? extends T> input)
C. public static <T> List<? extends T> backwards(List<T> input)
D. public static <T> List<? super T> backwards(List<T> input)

Now in C and D , the return type as <? extends T> and <? super T> both is valid. I am confused as to how both are possible for the output variable which is of type T . I know both <? extends T> and <? super T> include the type T , thats fine, but when the method returns output it is of type <T> and it cannot be converted to a subtype of <T>, I guess so how does <?extends T> become a valid choice?

Thanks in advance for helping on this issue...
 
megha joshi
Ranch Hand
Posts: 206
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sorry , I guess its late so my mind was not working. I found the answer.

The method returns <T> so declaring its return type as <? extends T> or <? super T> is valid as both include <T>.

Thanks..
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic