 |
Arrays
|
Introduction
-
An array is a language element that is a feature of most programming
languages
-
It supports collections of data, like a Vector:
-
consists of one or more positions
-
posistions indexed by an int
-
first position is 0
-
must be created with new
-
is an object
-
However it is different from a Vector:
-
Not a class - it is built into the language
-
There are no methods
-
There is a field, called length, to give the number of elements
(c.f. a method size for Vectors)
-
Arrays can hold primitive data types (like ints)
-
The type of elements in the array must be specified when the array is
declared. Everything stored in that array must be of that type.
-
Arrays can't grow.
Using arrays
-
To declare an array, you write the type of the data element it will hold,
followed by square brackets and then the name:
int [] lottoNumbers;
String [] winners;
Employee [] personnel;
Compare this with the parameter to the main method, which we've seen from
day one.
To create an array, use new, followed by element type, followed by desired
length in square brackets.
lottoNumbers = new int [6];
winners = new String [20];
personnel = new Employee [1000];
Anywhere in the program, we can now find out their lengths:
int numEmployees = personnel.length;
Notice, no brackets after length - it is not a method call.
To set the value of a particular position in the array, you use an assignment:
lottoNumbers[1] = 27;
To use the value of a position, you index it with square brackets
String line = winners[0] + winners[1];
Example, read in 100 integers and print them in reverse order
import java.io.*;
import cucs.*;
class ReverseIntegers {
public static void main (String [] args) {
BasicDataReader in = new BasicDataReader ();
int[] z = new int[100];
int i;
for (i=0; i != 100; i++) {
z[i] = in.readInt ();
}
for (i=100; i != -1; i--) {
System.out.println (z[i]);
}
}
}
Last modified: 4/19/99