Next: None. Up: The ArrayList class. Previous: The ArrayList class.


Wrapper classes

Textbook: Section 13.3

So what do you do when you want to store a primitive value into an ArrayList? Well, you use the wrapper classes, classes provided in the java.lang package. (Incidentally, java.lang is automatically imported in every Java program - it's the only such package in Java.)

For example, if you want to create an object to represent an int value 8, you'd create an instance of the Integer class.

Integer ival = new Integer(8);
This is something you can legitimately insert into an ArrayList.
count.add(new Integer(8));

Ok, it's there. But how do you access an int value from the ArrayList? Well, you have to remove the Integer instance and then call the intValue() method on it.

Integer out_obj = (Integer) count.get(0);
int out = out_obj.intValue();
Or, more succinctly (and confusingly):
int out = ((Integer) count.get(0)).intValue();

There are similar classes for all the primitive types: Boolean, Byte, Character, Double, Integer, Float, Long, and Short. Each has the appropriate xxxValue() method for extracting the primitive-type value from the object.

Yes, it's a pain. But it's the best way to get a primitive-type value into an ArrayList.

Exercise


Next: None. Up: The ArrayList class. Previous: Wrapper classes.