Tino APCS

The Wrapper Classes

Because numbers are not objects in Java, you cannot insert them directly into pre 1.5 ArrayLists. To store sequences of integers, floating-point numbers, or boolean values in a pre 1.5 ArrayList, you must use wrapper classes.

The classes Integer, Double, and Boolean wrap primitive values inside objects. These wrapper objects can be stored in ArrayLists.

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 a pre-Java 1.5 ArrayList, 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);`


Or the shorthand version:

grades.add(new Double(93.45));


To retrieve the number, you need to cast the return value of the get method to Double, and then call the doubleValue method:

wrapper = (Double)grades.get(0); 
testScore = wrapper.doubleValue();


With Java 1.5, declare your ArrayList to only hold Doubles. With a new feature called auto-boxing in Java 1.5, when you define an ArrayList to contain a particular wrapper class, you can put the corresponding primitive value directly into the ArrayList without having to wrap it. You can also pull the primitive directly out.

ArrayList grades2 <Double> =  new  ArrayList <Double>(); 
grades2.add(93.45);
System.out.println("Value is " + grades2.get(0));


Dark Mode

Outline