Hi Friends,
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:
Correct: 3 B, E, and F are correct.
Wrong: The return type of process is definitely declared as a List, not an ArrayList, so A and D
are wrong. C is wrong because the return type evaluates to List<Integer>, and that can't
be 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.
I tried to make a simple program for
testing above but I found something different. Can anyone tell me that if I am making a mistake in my program to test above example? And how to write a program so that above results are true ?
My Program:
import java.util.*;
public class NitGenericsTest2
{
public static <E extends Number> List<? super E> process(List<E> nums)
{
List <Number> a=null;
return a;
}
public static void main(
String args[])
{
System.out.println("Hi Nitin Inside main");
//ArrayList<Integer> input = null; // Option A
//ArrayList<Integer> output = null; // Option A
//ArrayList<Integer> input = null; // option B
//List<Integer> output = null;// option B
//ArrayList<Integer> input = null;// option C
//List<Number> output = null;// option C
//List<Number> input = null;// option D
//ArrayList<Integer> output = null;// option D
List<Number> input = null; // option E
List<Number> output = null; // option E
//List<Integer> input = null;// option F
//List<Integer> output = null;// option F
//List<Number> input = null;// This works
//List<? super Number> output = null;// This works
output = process(input);
}
}
As Options B, E and F are correct so I've used option E as my test case in above program. But I got the following compilation error:
can't convert from List<capture-of ? super Number> to List<Number> I believe that since option E is:
List<Number> output = null; but return type of method process() is
List<? super Number> so the given compilation error is coming.
If I change
List<Number>output to
List<? super Number>output then no compilation error.
Is Q 16 correct or are the answers B,E,F correct? Should the answer for Q16 not be G?
Thanks & Regards,
Nitin
[ August 14, 2007: Message edited by: Nitin Bhardwaj ]