Skip to main content
Lesson 20 - ArrayList
ZIPPDF (letter)
Lesson MenuPreviousNext
  
Wrapper Classes page 6 of 9

  1. 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.

  2. The classes Integer, Double, and Boolean wrap number and truth values inside objects. These wrapper objects can be stored inside array lists.

  3. 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();
  4. 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();
  5. 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.


Lesson MenuPreviousNext
Contact
 ©ICT 2003, All Rights Reserved.