File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics Question" Watch "Generics Question" New topic

Generics Question

subathra sangameswaran

Joined: Nov 19, 2005
Posts: 27
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:
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.
� 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!

Aleksander Zielinski
Ranch Hand

Joined: Nov 11, 2005
Posts: 127
I agree. Here's the link:
subject: Generics Question
It's not a secret anymore!