Wrapper Classes Use wrapper objects in Collections when you can’t use primitive types Primitive TypeWrapper Class byteByte shortShort intInteger longLong floatFloat doubleDouble charCharacter booleanBoolean
Wrapper Classes For example: Integer age = new Integer(40); Wrapper classes contain static methods to convert between types. For example, to convert a String to an int : int num = Integer.parseInt(str); Wrapper classes also contain constants such as MIN_VALUE and MAX_VALUE in the Integer class, which hold the smallest and largest int values Copyright © 2012 Pearson Education, Inc.
Wrapping: Converting from primitive to wrapper Use the wrapper class constructor to instantiate a new object. Example Character characterVar; Integer myInteger; char myChar = ‘z’; characterVar = new Character( myChar ); myInteger = new Integer( 1234 ); Unwrapping: Converting from wrapper to primitive int myInt; char myChar = ‘z’; myChar = characterVar.charValue(); myInt = myInteger.intValue(); Example Apply the conversion method to the wrapper object.
A SimpleList Problem. Solution SimpleList list = new SimpleList(); list.insert( new Double(53.1) ); Example SimpleList list = new SimpleList(); list.insert( 53.1 ); ^ Incompatible type for method. Can’t convert double to java.lang.Object