Java Reference
In-Depth Information
Whenever a value of a primitive type is used in a context that requires a wrapper type, the com-
piler automatically wraps the primitive-type value in an appropriate wrapper object. This means
that primitive-type values can be added directly to a collection:
private ArrayList<Integer> markList;
...
public void storeMarkInList(int mark)
{
markList.add(mark);
}
The reverse operation— unboxing —is also performed automatically, so retrieval from a collec-
tion might look like this:
int firstMark = markList.remove(0);
Autoboxing is also applied whenever a primitive-type value is passed as a parameter to a
method that expects a wrapper type and when a primitive-type value is stored in a wrapper-type
variable. Similarly, unboxing is applied when a wrapper-type value is passed as a parameter
to a method that expects a primitive-type value and when stored in a primitive-type variable.
It is worth noting that this almost makes it appear as if primitive types can be stored in collec-
tions. However, the type of the collection must still be declared using the wrapper type (e.g.,
ArrayList<Integer> , not ArrayList<int> ).
8.10
The collection hierarchy
The Java library uses inheritance extensively in the definition of the collections classes. Class
ArrayList , for example, inherits from a class called AbstractList , which, in turn, inherits
from AbstractCollection . We shall not discuss this hierarchy here, because it is described
in detail at various easily accessible places. One good description is at Oracle's web site at
http://download.oracle.com/javase/tutorial/collections/index.html.
Note that some details of this hierarchy require an understanding of Java interfaces. We discuss
those in Chapter 10.
Exercise 8.15 Use the documentation of the Java standard class libraries to find out about
the inheritance hierarchy of the collection classes. Draw a diagram showing the hierarchy.
8.11
Summary
This chapter has presented a first view of inheritance. All classes in Java are arranged in an
inheritance hierarchy. Each class may have an explicitly declared superclass, or it inherits im-
plicitly from the class Object .
Subclasses usually represent specializations of superclasses. Because of this, the inheritance
relationship is also referred to as an is-a relationship (a car is-a vehicle).
 
 
 
Search WWH ::




Custom Search