• 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 Question

 
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
https://coderanch.com/t/253083/java-programmer-SCJP/certification/SJCP-Study-Guide-generics-collections
 
reply
    Bookmark Topic Watch Topic
  • New Topic