• 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
  • Ron McLeod
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Rob Spoor
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Carey Brown
Bartenders:

K&B Mock question on generics

 
Ranch Hand
Posts: 232
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello,

Ref: K&B Chapter 7: Generics and Collections
Question/Answer 16 in page 634:


Given a method declared as:

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.



According to book the answer is B, E and F.

I answered G since they all look like incorrect to me (maybe some more studying with generics).

So i decided to test: Nothing worked.
See comments in the code.


public class SCJP {
// if you rename return type List<? super E> to List<E> it's compiling
public static <E extends Number> List<? super E> process(List<E> nums){
List <E> l = null; //is this correct?
return l;
}
public static void main(String[] args){
//answer B
ArrayList<Integer> input = null;
List<Integer> output = null;
output = process(input); // incompatible types says Intellij Idea 7.0.1 if return type is List<? super E>
}
}



Can some one please explain me what is correct and what's not. What i'm missing here?
 
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Check the Errata, the correct method signature is:
public static <E extends Number> List<E> process(List<E> nums) {
 
Jari Timonen
Ranch Hand
Posts: 232
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Method signature is copied straight from pdf.. That's why i'm asking
Althoug it's missing from the question in my first post.
[ November 24, 2007: Message edited by: Jari Timonen ]
 
reply
    Bookmark Topic Watch Topic
  • New Topic