Wrapper Classes
Wrapper Classes
- 24 -
Wrapper Classes
...but sometimes it would be useful to have objects
hold primitive data.
Example
To include different primitive data types in a single Object[] array.
Wrapper Classes
– Classes for “wrapping” primitive data in objects.
– All override the Object methods toString, equals, and hashCode.
– All wrapper classes (except for Boolean) implement the
Comparable interface (implement compareTo())
- 25 -
UML Class Diagram for Wrapper Classes
- 26 -
- 27 -
Example: Constructing Wrapped
Numbers
Double doubleObject = new Double(5.0);
Double doubleObject = new Double(“5.0”);
Double doubleObject = Double.valueOf(“12.4”)
- 28 -
Converting Between Strings and
Primitive Numeric Types
Converting to String
Double doubleObject = new Double(5.0);
String s = doubleObject.toString();
- 29 -
Example: A Polymorphic (“Generic”)
Sorting Method
Text Example, GenericSort.java
(implementation of Selection Sort: iteratively finds largest
element, places it at the end of the array)
• Using the Comparable interface (compareTo()),
different object types are sorted using the same sorting
method; each class defines how objects of the class
should be ordered.
- 30 -
Automatic Conversion Between Primitive
and Wrapper Class Types
‘Boxing’
Converting primitive → wrapper
e.g. Integer[ ] intArray = {1, 2, 3};
e.g. Integer intObject = 2; // both legal, ‘autoboxing’ occurs
‘Unboxing’
Converting wrapper → primitive
e.g. System.out.println(intArray[0] + intArray[1] + intArray[2]);
// int values are summed before output.
e.g. int i = new Integer(3); // legal, ‘autounboxing occurs’
Automatic Conversions
– Compiler will box for contexts requiring an object
– Compiler will unbox for contexts requiring a primitive
- 31 -