CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Collections

Collections and Generics
Legacy collections
Wrapper classes

How to use wrapper classes with untyped collections

  • Because untyped collections can't hold primitive types, you must use wrapper classes to store primitive types in them.
  • To add a primitive type to an untyped collection:
    • create an instance of the appropriate wrapper class
    • pass the value you want it to hold to the constructor of that class
  • You can assign the wrapper type to a primitive type variable without any explicit casting. To retrieve an element that holds a primitive type, cast the element to the wrapper type.

Wrapper classes for primitive types

Primitive type Wrapper class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Char
boolean Boolean

Code that adds integers to an untyped array list

ArrayList numbers = new ArrayList();

numbers.add(new Integer(1));
numbers.add(new Integer(2));
numbers.add(new Integer(3));
Code that retrieves integers from the array list
for (int i = 0; i < numbers.size(); i++)
{
    int number = (Integer)numbers.get(i);
    System.out.println(number);
}

Resulting output

1
2
3
Previous | Introduction | Untype collection | Wrapper classes