ProblemYou need to convert numbers to objects and objects to numbers. SolutionUse the Object Wrapper classes listed in Table 5-1 at the beginning of this chapter. DiscussionOften you have a primitive number and you need to pass it into a method where an Object is required. This frequently happens when using the Collection classes (see Chapter 7) in 1.4 and earlier (in 1.5 you can use AutoBoxing, described in Recipe 8.4). To convert between an int and an Integer object, or vice versa, you can use the following: // IntObject.java // int to Integer Integer i1 = new Integer(42); System.out.println(i1.toString( )); // or just i1 // Integer to int int i2 = i1.intValue( ); System.out.println(i2); |