Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt in generics example from kathy sierra

 
kaushal rathore
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?

The correct answers are:

B. ArrayList<Integer> input = null;
List<Integer> output = null;

E. List<Number> input = null;
List<Number> output = null;

F. List<Integer> input = null;
List<Integer> output = null;


Doubt:
we can assign List<E> type to List<? super E> type
but can we assign conversly List<? super E> to List<E> as we are doing in above example because the method "process" is returning List<? super E> and in correct answers we are assigninig this returning value "List<? super E>" to a "List<E> output" refrence?
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Howdy Kaushal,

seems to be your first or second posting here so

Welcome to the Ranch!



You were right in saying that we cannot assign a List<? super E> to a List<E>.
But we are not doing that in the example.
The return type is List<? super E>
and we return an List<E> in all three examples.
But this is
assigning a List<E> to a List<? super E> and not
assigning a List<? super E> to a List<E>.

And <? super E> also include E itself, but I'm sure you knew that.

Yours,
Bu.
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also see the errata:

K&B SCJP Errata

Thanks,
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic