[SCJP] Generics & wildcard
Bonjour,
Je suis entrain de faire quelques tests pour la SCJP et la je suis au chaptire Generics, du livre SCJP for JAva 5 Sutdy Guide bu Kathy Sierra & Bert Bates.
Ci dessous la question, les choix possibles et la reponse:
Questions :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
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. |
Ok Reflechissez un Instant la...
Encore un peu...
Ok Voila la reponse du livre:
Code:
1 2 3 4 5 6 7 8
|
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 D
are wrong. C is wrong because the return type evaluates to List<Integer>, and that can't
be assigned to a variable of type List<Number>. Of course all these would probably cause a
NullPointerException since the variables are still nullbut the question only asked us
to get the code to compile. |
ok c un peu tricky mais j ai compris les reponses, mais voilamon problem:
j ai voulu tester les examples en ecrivant un bout de code
Code:
1 2 3 4 5 6 7 8 9 10
|
public static void main(String [] args){
ArrayList<Integer> input = null;
List<Integer> output = null;
output = process(input);
}
public static <E extends Number> List<? super E> process(List<E> nums){
List<E> test = new ArrayList<E>();
return test;
} |
et la quand j'ai cette erruer de compilation a la ligne output = process(input)
Code:
1 2 3
|
Severity and Description Path Resource Location Creation Time Id
Type mismatch: cannot convert from List<String> to ArrayList<String> Java_Certifiacation GenericsTestEx.java line 6 1186410140671 21008 |
Si vous pouvez m'eclairer SVP, Je ne comprend pas l erruer, ou est ce que je me suis trompe et je ne crois pas vraiment que Kathy Sierra and Bert Bates se sont trompes,
Merci pour tout....