|
JavaFAQ Home » Java Notes by Fred Swartz

All arrays in Java are really linear, one-dimensional arrays.
However, you can easily build multi-dimensional arrays
from these, and Java has features in the language to help
you do this.
These examples all use two-dimensional arrays,
but the same syntax and coding can easily be extended to
arrays of any dimension. By convention two dimensional
arrays have rows (horizontal) and
columns (vertical). The first subscript selects
the row (which is a one-dimensional array itself),
and the second subscript selects the element in that row/array.
Visualizing two-dimensional arrays
Assume we have an array, a, with three rows and four columns.
| a[0][0] | a[0][1] | a[0][2] | a[0][3] |
| a[1][0] | a[1][1] | a[1][2] | a[1][3] |
| a[2][0] | a[2][1] | a[2][2] | a[2][3] |
|
Two-dimensional arrays are usually visualized as a matrix, with
rows and columns. This diagram shows the array a with
its corresponding subscripts.
|
+-----+
| | +-----+-----+-----+-----+
|a[0] | -> | [0] | [1] | [2] | [3] |
| | +-----+-----+-----+-----+
+-----+
| | +-----+-----+-----+-----+
|a[1] | -> | [0] | [1] | [2] | [3] |
| | +-----+-----+-----+-----+
+-----+
| | +-----+-----+-----+-----+
|a[2] | -> | [0] | [1] | [2] | [3] |
| | +-----+-----+-----+-----+
+-----+ |
In Java two-dimensional arrays are implemented is a one-dimensional array
of one-dimensional arrays -- like this. |
Declaring and Allocating a two-dimensional array
Let's declare a board for playing the game of tic-tac-toe.
It will have three rows (the first subscript) and three columns
(the second subscript) and contain an int in each element.
int[][] board = new int[3][3];
Initial values
It's possible to assign initial values to an array when
you declare it in a manner very similar to one-dimensional
arrays, but with an extra level of braces.
int[][] board = new int[3][3] {{0,0,0},{0,0,0},{0,0,0}};
You must assign values to an element before you
use it, either with an initializer as above or assignment.
Example -- drawing the tic-tac-toe board
It's often easiest to use two-dimensional arrays with nested
for loops. For example, the following code
draws the tic-tac-toe board in a paint method.
It assumes that a cell is 10 pixels on a side, and that
a positive number represents an X and a negative number
represents an O.
for (int row=0; row<3; row++) {
for (int col=0; col<3; col++) {
if (board[row][col] > 0) { // draw X
g.drawLine(col*10, row*10 , col*10+8, row*10+ ;
g.drawLine(col*10, row*10+8, col*10+8, row*10 );
} else if (board[row][col] < 0) { // draw O
g.drawOval(col*10, row*10, 8, ;
}
}
}
Printer Friendly Page
Send to a Friend
..
Search here again if you need more info!
|