Cover Data Structures and Algorithms with Object-Oriented Design Patterns in Java
next up previous contents index

Wrappers for the Primitive Types

 

The primitive types  in Java are boolean, char, short, int, long, float, and double. There is also the ``type'' void which is used in the place of the return type to declare a method that returns nothing. For each primitive type, the Java language defines a class that wraps  the primitive. The wrapper classes are called Boolean, Character, Short, Integer, Long, Float, and Double. There is also a wrapper class for void called Void.

Like all Java classes, the wrapper classes are ultimately derived from the Object class. Therefore, they all provide an equals method to test for equality. However, because the wrapper classes do not implement the Comparable interface given in Program gif, the comparison methods isLT, isLE, isGT, isGE, isEQ, and isNE are not supported.

To circumvent this shortcoming, we might be tempted to extend the wrapper classes like this:

class ComparableInteger
    extends Integer // Wrong.  Integer is a final class!
    implements Comparable
{
     // ...
}
Unfortunately, according to the Java language specification, the Integer class is a final class--it cannot be extended[16].

Consequently, we are forced to implement our own wrapper classes if we want them to implement the Comparable interface. Programs gif, gif and gif define the four such wrapper classes Chr, Int, and Dbl, which are wrappers for Java primitive types char, int, and double.

   program4447
Program: Chr class.

   program4458
Program: Int class.

   program4469
Program: Dbl class.

Java also provides a String class for dealing with character sequences. The String class is special in that it is closely tied to the definition of the language itself. The Java compiler automatically creates a String object for every string literal , such as "Hello world.\n", in a Java program.

Because the String class does not implement the Comparable interface and because the String class cannot be extend, we are forced to implement a wrapper class. Program gif defines the class Str which wraps a String instance and implements the Comparable interface.

   program4492
Program: Str class.


next up previous contents index

Bruno Copyright © 1998 by Bruno R. Preiss, P.Eng. All rights reserved.