1 import java.util.ArrayList;
2 import java.util.Iterator;
3
4 public class UnsafeDemo2
5 {
6 public static void main(String[] args)
7 {
8 ArrayList<Integer> numbers = new ArrayList<Integer>();
9 numbers.add(1);
10 numbers.add(2);
11 numbers.add(3);
12 print(numbers);
13 System.out.println("Sum: " + sum(numbers));
14 numbers.add("4"); // Compiler error message
15 print(numbers);
16 System.out.println("Sum: " + sum(numbers));
17 }
18
19 public static void print(ArrayList<Integer> lst)
20 {
21 Iterator<Integer> iter = lst.iterator();
22 while (iter.hasNext())
23 {
24 System.out.print(iter.next() + " ");
25 }
26 System.out.println();
27 }
28
29 public static int sum(ArrayList<Integer> lst)
30 {
31 int sum = 0;
32 Iterator<Integer> iter = lst.iterator();
33 while (iter.hasNext())
34 {
35 sum = sum + iter.next(); // No cast needed
36 }
37 return sum;
38 }
39 }