• Wrapper classes
    • Collections can only hold object references, not primitives
    • Each primitive type has a corresponding "wrapper class"
    • E.g. int has Integer as wrapper class
    • Collection can be of Wrapper class type: ArrayList<Integer>
    • To insert a primitive value into collection, first "wrap" it: Integer x = new Integer(17)
    • To access primtive value in a wrapper class object: x.intValue()
    • Prior to Java 5:
    • java.util.HashSet<Integer> numbers;
      numbers = new java.util.HashSet<Integer>();
      numbers.add(new Integer(3));
      numbers.add(new Integer(5));
      // a foreach loop to calculate the sum of all
      // the items in the HashSet numbers:
      int sum = 0;
      for (Integer i: numbers) {
          sum = sum + i.intValue();
      }
      System.out.println("Sum is "+sum);
      
    • Starting with Java 5, language has a feature called "autoboxing" and "autounboxing": code doesn't need to explicitly wrap or unwrap primitives:
    • java.util.HashSet<Integer> numbers;
      numbers = new java.util.HashSet<Integer>();
      numbers.add(3);
      numbers.add(5);
      // a foreach loop to calculate the sum of all
      // the items in the HashSet numbers:
      int sum = 0;
      for (Integer i: numbers) {
          sum = sum + i;
      }
      System.out.println("Sum is "+sum);
      
  • Lab 9 questions