Computer Science 15-100 (Sections T & U), Fall 2007
Class Notes:   Array Lists and Wrapper Classes


Logistics

  1. Reading:  L&L Sections on ArrayLists and Wrapper Classes

Code from Class:
// Here is the code we wrote from class today,
// to demonstrate ArrayLists and Wrapper Classes

import java.util.ArrayList;

@SuppressWarnings("unchecked")
class WrapperClassAndAutoboxingDemo {
  public static void main(String[] args) {
    int[] a1 = new int[5];
    ArrayList a2 = new ArrayList();
    
    a1[0] = 22;
    // a2.set(0,22);  // not yet!
    
    // AUTOBOX:  turns primitive type (int) into reference type (Integer)
    a2.add(22); // same as::   a2.add(new Integer(22));
    
    System.out.println(a1[0]);
    System.out.println(a2.get(0));

    a2.set(0,"wahoo");
    System.out.println(a2.get(0));

    a2.set(0,33);  // not yet!
    System.out.println(a2.get(0));
    
    // a1[0] = "bummer"; // will not work!
    
    System.out.println(a1[0] + a1[0]); // prints 44 (22 + 22)

    // System.out.println(a2.get(0) + a2.get(0)); // WILL NOT COMPILE
    System.out.println((Integer)a2.get(0) + (Integer)a2.get(0)); // prints 66 (33 + 33)

    Integer i3 = (Integer) a2.get(0);
    // AUTO-UNBOX:  turns reference type (Integer) into primitive type (int)
    int i0 = (Integer)a2.get(0);
    System.out.println(i0 + i0); // prints 66 (33 + 33)
    
    Integer i1 = new Integer(56);
    // AUTO-UNBOX:  turns reference type (Integer) into primitive type (int)
    System.out.println(i1 + i1);
    
  }
}

Carpe diem!