UnsafeDemo.java.html

  1  public class UnsafeDemo
  2  {
  3     public static void main(String[] args)
  4     {
  5        // Here, we use the linked list class from Chapter 16
  6        LinkedList numbers = new LinkedList();
  7        numbers.addFirst(1);
  8        numbers.addFirst(2);
  9        numbers.addFirst(3);
 10        print(numbers);
 11        System.out.println("Sum: " + sum(numbers));
 12        numbers.addFirst("4"); // No error message
 13        print(numbers); // No error
 14        System.out.println("Sum: " + sum(numbers));
 15           // ClassCastException
 16     }
 17  
 18     public static void print(LinkedList lst)
 19     {
 20        ListIterator iter = lst.listIterator();
 21        while (iter.hasNext())
 22        {
 23           System.out.print(iter.next() + " ");
 24        }
 25        System.out.println();
 26     }
 27  
 28     public static int sum(LinkedList lst)
 29     {
 30        int sum = 0;
 31        ListIterator iter = lst.listIterator();
 32        while (iter.hasNext())
 33        {
 34           sum = sum + (Integer) iter.next();
 35        }
 36        return sum;
 37     }
 38  }