Wrapper classes for primitive types:
| Primitive type | Wrapper class |
| byte | Byte |
| short | Short |
| int | Interger |
| long | Long |
| float | Float |
| double | Double |
| char | Char |
| boolean | Boolean |
Example 1: Code that adds integers to an untyped array list:
ArrayList number = new ArrayList(); nubers.add(new Integer(1)); nubers.add(new Integer(2)); nubers.add(new Integer(3));
Example 2: Code that retrieves intergers from the array list:
for (int i = 0; numbers.size(); i++) { int number = (Integer)numbers.get(i); System.out.pringln(number); }
Description:
-
Because untyped collections hold elements of thpe Object, they can't hold primitive types. As a result you must use wrapper claases to store primitive types in a collection.
-
To add a primitive type to an untyped collectio, create an instance of the appropriate wrapper class and pass the value you want it to hold to the construtor of that class.
-
To retrieve an element that holds a primitive type, cast the element to the wrapper type.