CJCoding With Joseph
15per day
← Back to Question List
Java Code Walkthrough #46

Generic Method with Bounded Wildcard

hardGenerics, Methods

📄 Code

Read carefully — what does this print?
1import java.util.ArrayList;
2import java.util.List;
3 
4public class Main {
5 public static double sumList(List<? extends Number> list) {
6 double total = 0;
7 for (Number n : list) {
8 total += n.doubleValue();
9 }
10 return total;
11 }
12 
13 public static void main(String[] args) {
14 List<Integer> ints = new ArrayList<>();
15 ints.add(1);
16 ints.add(2);
17 ints.add(3);
18 
19 List<Double> doubles = new ArrayList<>();
20 doubles.add(1.5);
21 doubles.add(2.5);
22 
23 System.out.println(sumList(ints));
24 System.out.println(sumList(doubles));
25 }
26}

🎯 Your Answer

← Previous