Arrays |
| BASIC |
An array allows you to have many values, without having to declare a separate variable to hold each one.
All the values in an array must be of the same type;
this is called the base type of the array. The array itself is said to
be of type "array of base type." For example, if the base type
is int, then the array type is "array of int."
The syntax for declaring an array is:
accessType optionalStatic baseType[] arrayName;
where
accessType is one of the access
types public, protected, omitted (meaning "package"),
or private,optionalStatic is either the keyword static
or is omitted (meaning "instance"),baseType is the type of value permitted in the array;
if the type is a class or interface
name, then values of any subclass of that
class are also permitted; andarrayName is a name chosen by the programmer to use
when referring to the array.For example,
public int scores[];
Notice that the length of the array (the number of values it can hold) is not part of the declaration. Rather, it is part of the value assigned to the array. For example, an array value might be
new int[35]
This is not a statement by itself, but an expression that creates a new array of the given length. It can be used as an initial value of the array,
public int scores[] = new int[35];
or a value can be assigned to the variable scores at some later
time:
scores = new int[43];
Either way, this is called defining the array, as opposed to declaring
the array. An array variable that has been declared but not defined has the
special value null, and there isn't much you can do with such a
variable.
You access the individual values in an array by indexing into it, using the
syntax arrayName[index]. The first value in the
array has index 0 (zero); the last value in the array has
the index .
To access each element in turn, you would typically use a for
loop.
Despite having a special syntax, strings are objects.
| INTERMEDIATE |
The values in an array can themselves be arrays. There is a special syntax for this, as in the following examples:
public double elevation[][]; // declaration
elevation = new double[50][75]; // defines an array with 50 rows and 75 columns
elevation[i][j + 1] = elevation[i][j] + 0.05; // using the array
These arrays are referred to as two-dimensional arrays. Arrays may have three, four, or even more dimensions.
| ADVANCED |
The values in an array can themselves be arrays, but these arrays need not all be the same size. If they are of different sizes, the result is a ragged array. For example, the following code constructs a "triangular" array, in which each sub-array is larger than the one preceding it:
int[] triangle = new int[10];
for (int i = 0; i < triangle.length; i++) {
triangle[i] = new int[i + 1];
}