Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics Question

 
subathra sangameswaran
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all!
I cannot understand this question and answer!

Given a method declared as:
public static <E extends Number> List<? super E> process(List<E> nums)
A programmer wants to use this method like this:
// INSERT DECLARATIONS HERE
output = process(input);
Which pairs of declarations could be placed at // INSERT DECLARATIONS HERE to allow
the code to compile? (Choose all that apply.)
A. ArrayList<Integer> input = null;
ArrayList<Integer> output = null;
B. ArrayList<Integer> input = null;
List<Integer> output = null;
C. ArrayList<Integer> input = null;
List<Number> output = null;
D. List<Number> input = null;
ArrayList<Integer> output = null;
E. List<Number> input = null;
List<Number> output = null;
F. List<Integer> input = null;
List<Integer> output = null;
G. None of the above.
Answer:
� 3 B, E, and F are correct.
�˚ The return type of process is definitely declared as a List, not an ArrayList, so A and Dare wrong. C is wrong because the return type evaluates to List<Integer>, and that can'tbe assigned to a variable of type List<Number>. Of course all these would probably cause a
NullPointerException since the variables are still null�but the question only asked us to get the code to compile.
--------------------------------------------------------
why cannot we return as well an ArrayList, when we can receive an ArrayList as argument to the method?As far as i understand collection reference and object can be polymorphic, but not their type!
If List<Integer> cannot be assigned to List<Number>, what does the return <? super E> mean?Why is c answer incorrect?

Thanks in advance!
Suba
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic