Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

K&B Mock question on generics

 
Jari Timonen
Ranch Hand
Posts: 232
  • Mark post as helpful
  • send pies
  • 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?
 
ahmed yehia
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
  • 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
  • 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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic