| |
Wrapper Classes | page 6 of 9 |
Because numbers are not objects in Java, you cannot insert them directly into array lists. To store sequences of integers, floating-point numbers, or boolean values in an array list, you must use wrapper classes.
The classes Integer , Double , and Boolean wrap number and truth values inside objects. These wrapper objects can be stored inside array lists.
The Double class is a typical number wrapper. There is a constructor that makes a Double object out of a double value:
Double r = new Double(8.2057);
Conversely, the doubleValue method retrieves the double value that is stored inside the Double object
Double d = r.doubleValue();
To add a primitive data type to an array list, you must first construct a wrapper object and then add the object. For example, the following code adds a floating-point number to an ArrayList :
ArrayList grades = new ArrayList();
double testScore = 93.45;
Double wrapper = new Double(testScore);
grades.add(wrapper);
To retrieve the number, you need to cast the return value of the get method to Double , and then call the doubleValue method:
Double wrapper = (Double)grades.get(0);
double testScore = wrapper.doubleValue();
The ArrayList class contains an Object[] array to hold a sequence of objects. When the array runs out of space, the ArrayList class allocates a larger array.
|