Java Reference
In-Depth Information
6.2
Arrays and References
A little more than kin, and less than kind.
WILLIAM SHAKESPEARE,
Hamlet
Just like a variable of one of the class types you have seen, a variable of an array type
holds a reference. In this section, we explore the consequences of this fact, including a
discussion of array parameters. We will see that arrays are objects and that array types
can be considered class types, but somewhat different kinds of class types than what
you are used to. Arrays and the kinds of classes we have seen before this chapter are
a little more than kin, and less than kind.
Arrays Are Objects
There are two ways to view an array: as a collection of indexed variables and as a single
item whose value is a collection of values of the base type. In Section 6.1, we discussed
using arrays as a collection of indexed variables. We will now discuss arrays from the
second point of view.
An array can be viewed as a single item whose value is a collection of values of the
base type. An array variable (as opposed to an array indexed variable) names the array as
a single item. For example, the following declares a variable of an array type:
double [] a;
This variable a can and will contain a single value. The expression
new double [10]
creates an array object and stores the object in memory. The following assignment
statement places a reference to (the memory address of) this array object in the variable a :
a = new double [10];
Typically, we combine all this into a single statement as follows:
double [] a = new double [10];
Notice that this is almost exactly the same as the way that we view objects of a class
type. In Java, an array is considered an object . Whenever Java documentation says that
something applies to objects, it means that it applies to arrays as well as objects of the
class types we have seen up to now. You will eventually see examples of methods that
can take arguments that may be objects of any kind. These methods will accept array
objects as arguments as well as objects of an ordinary class type. Arrays are somewhat
peculiar in how they relate to classes. Some authorities say array types are not classes
 
 
Search WWH ::




Custom Search