Java Reference
In-Depth Information
Do something with a
If you don't need to look at all of the elements, use an ordinary loop
instead. For example, to skip the initial element, you can use this loop.
for (int i = 1; i < accounts.size(); i++)
{
BankAccount a = accounts.get(i);
Do something with a
}
309
310
For arrays, you use .length instead of .size() and [i] instead of
.get(i) .
A DVANCED T OPIC 7.2: Two-Dimensional Arrays with
Variable Row Lengths
When you declare a two-dimensional array with the command
int[][] a = new int[5][5];
then you get a 5-by-5 matrix that can store 25 elements:
a[0][0] a[0][1] a[0][2] a[0][3] a[0][4]
a[1][0] a[1][1] a[1][2] a[1][3] a[1][4]
a[2][0] a[2][1] a[2][2] a[2][3] a[2][4]
a[3][0] a[3][1] a[3][2] a[3][3] a[3][4]
a[4][0] a[4][1] a[4][2] a[4][3] a[4][4]
In this matrix, all rows have the same length. In Java it is possible to declare arrays
in which the row length varies. For example, you can store an array that has a
triangular shape, such as:
b[0][0]
b[1][0] b[1][1]
b[2][0] b[2][1] b[2][2]
b[3][0] b[3][1] b[3][2] b[3][3]
b[4][0] b[4][1] b[4][2] b[4][3] b[4][4]
To allocate such an array, you must work harder. First, you allocate space to hold
five rows. Indicate that you will manually set each row by leaving the second array
index empty:
Search WWH ::




Custom Search