Given a pre-generics implementation of a method:
11. public static int sum(List list) {
12. int sum = 0;
13. for ( Iterator iter = list.iterator(); iter.hasNext(); ) {
14. int i = ((Integer)iter.next()).intValue();
15. sum += i;
16. }
17. return sum;
18. }
What three changes allow the class to be used with generics and avoid an unchecked warning? (Choose
three.)
A. Remove line 14.
B. Replace line 14 with "int i = iter.next();".
C. Replace line 13 with "for (int i : intList) {".
D. Replace line 13 with "for (Iterator iter : intList) {".
E. Replace the method declaration with "sum(List<int> intList)".
F. Replace the method declaration with "sum(List<Integer> intList)".
Answer: ACF
本道题考查:
allow the class to be used with generics and avoid an unchecked warning
允许使用泛型类,避免一个不用检查的警告。
我在eclipse里敲了下代码,
public int sum(List<Integer> list) {
int sum = 0;
//第一种写法:
// for(int i: list){
// sum += i;
// }
for (Iterator<Integer> iterator = list.iterator(); iterator.hasNext();) {
int i = iterator.next();
sum += i;
}
return sum;
}
foreach的写法很是方便,第二种写法也可以,就是有点麻烦。