Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics K&B Mock exam question

 
megha joshi
Ranch Hand
Posts: 206
  • 0
  • Mark post as helpful
  • send pies
  • 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
  • 0
  • Mark post as helpful
  • send pies
  • 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..
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic