Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^486) | One-Dimensional Arrays
Let’s now define Java arrays formally and look at the rules for accessing individual
components.


Declaring an Array


A one-dimensional arrayis a structured collection of components (often called array
elements) that can be accessed individually by specifying the position of a com-
ponent with a single index value.
Here is a syntax template describing the simplest form of a one-dimensional
array declaration:

In the syntax template, Data-Type describes what is stored in each component of the array.
The brackets following Data-Type indicate that this structure is an array of Data-Type ele-
ments. Array components may be of almost any type, but for now we limit our discussion to
atomic components. From Figure 10.1, we know that the array is a reference type. Array-
Name is a location in memory that will hold the address of an array when that array is
instantiated. For example,

int[] numbers;

declares a variable that can hold the address of an array of integers. We tell the compiler how
many components the array contains when we instantiate it.

Creating an Array


You create an array just like you create an object; you use new. Following is the syntax tem-
plate for instantiating an array. Notice that arrays don’t need to be initialized, so we don’t pass
a list of arguments. Instead, we put the number of slots to be in the array in brackets beside
the type of the array.

Int-Expression is an integer expression that specifies the number of components in the ar-
ray. This expression must have a value greater than or equal to 0. If the value is n, the range
of index values is 0 through n1, not 1 through n. For example, the declarations

Array-Creation

Array-Name = new Data-Type[IntExpression];

Data-Type [] Array-Name;

Array-Declaration

One-dimensional array A
structured collection of compo-
nents, all of the same type, that
is given a single name. Each
component (array element) is
accessed by an index that indi-
cates the component’s position
within the collection.
Free download pdf