An array is a sequence of consecutive memory locations for storing values of the same type. The type of those values are called base type. Each value in the array is called an element. Each element can be accessed by a nonnegative integer index. E.g., for an array a
containing 4 elements, the elements are denoted a[0]
, a[1]
, a[2]
, and a[3]
. Each element is used exactly like a variable of the base type, e.g.,
a[1] = 3;
a[2] = a[1] + 4;
An array is a random-access data structure, i.e., the time to access an element is about the same as any other. This access time is a constant.
To declare an array varible, write
BaseType [] a;
To create an array and also assign to a variable, write
a = new BaseType [size];
To initialize an array, write
for (int i = 0; i < a.length; i++)
a[i] = i;
Array variable declaration & array creation can be combined like so:
BaseType [] a = new BaseType [10];
Java initializes data in objects using default values: 0
for numeric types, false
for boolean type, null
for String and object types. So, explicit initialization needs only be done if we want the initial values to be different from the default values. Another implication is that creating an array takes time proportional to the length of the array.
Double.NEGATIVE_INFINITY
Double.POSITIVE_INFINITY
Integer.MIN_VALUE
Integer.MAX_VALUE
Long.MIN_VALUE
Long.MAX_VALUE
sum
, min
, max
, average
ArrayIndexOutOfBounds
exception if the program tries to access elements with index <0 or >length − 1We can set values of an array at compile time at its declaration like so.
String[] coinFlip = { "Head", "Tail" };
The new operator can be used to create and initialize a new array object at the same time. E.g.
makeButtons( new String[] { "Stop", "Go", "Next", "Previous" } );
So we can also do this
int[] primes = new int[] { 2, 3, 5, 7 };
Sample.java
shows how to do “sampling without replacement.” Suffling a deck of card is an example application of sampling without replacement.An interesting way to use arrays is to store precomputed values.
String[] day = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
Applying assignment (=) and comparison (==) operators to arrays does not mean the same same thing as applying these operations to numeric types.
<www.stat.stanford.edu/~susan/surprise/Collector.html>
Example usage:
double[][] a;
a = new double[m][n];
for (int i = 0; i < m; i++)
for (int i = 0; i < n; i++)
a[i][j] = 0.0;
Example program: SelfAvoidingWalk.java