Java Reference
In-Depth Information
Figure 8.10
All classes inherit from
Object
Having a common superclass for all objects serves two purposes: First, we can declare polymor-
phic variables of type
Object
to hold any object. Having variables that can hold any object type is
not often useful, but there are some situations where this can help. Second, the
Object
class can
define some methods that are then automatically available for every existing object. Of particular
importance are the methods
toString
,
equals
, and
hashCode
which
Object
defines. This sec-
ond point becomes interesting a bit later, and we shall discuss this in more detail in the next chapter.
8.9
Autoboxing and wrapper classes
We have seen that, with suitable parameterization, the collection classes can store objects of
any object type. There remains one problem: Java has some types that are not object types.
As we know, the simple types—such as
int
,
boolean
, and
char
—are separate from object
types. Their values are not instances of classes, and they do not inherit from the
Object
class.
Because of this, they are not subtypes of
Object
, and it would not normally be possible to add
them into a collection.
This is unfortunate. There are situations in which we might want to create a list of
int
values or
a set of
char
values, for instance. What can we do?
Concept:
Autoboxing
is
performed auto-
matically when a
primitive-type value
is used in a context
requiring a wrapper
type.
Java's solution to this problem is
wrapper classes.
Every primitive type in Java has a corre-
sponding wrapper class that represents the same type but is a real object type. The wrapper class
for
int
, for example, is called
Integer
. A complete list of simple types and their wrapper
classes is given in Appendix B.
The following statement explicitly wraps the value of the primitive
int
variable
ix
in an
Integer
object:
Integer iwrap = new Integer(ix);
And now
iwrap
could obviously easily be stored in an
ArrayList<Integer>
collection, for
instance. However, storing of primitive values into an object collection is made even easier
through a compiler feature known as
autoboxing.
Search WWH ::
Custom Search