The Department of Computer Science & Engineering |
STUART C. SHAPIRO: CSE
115 C
|
An array is a random-access data structure that can hold a
number of objects of the same type.
Notice that RAM is an array of bytes.
Declaration: type[] _array;
for any type
.
Notice that type[]
is a type, and can be used
for formal parameters as well as declaring variables.
Creation: _array = new type[length];
After initialization, _array
holds a reference
to an object that, in turn, holds length
many
"variables" of type type
.
As objects, arrays have attributes. In particular
_array.length
.
To refer to one of the "variables" held by
_array
, use _array[i]
,
for 0 <= i < _array.length
.
bsh % int[] a = new int[5]; bsh % print(a.length); 5 bsh % for (int i=0; i<a.length; i++) a[i] = i*i; bsh % for (int i=0; i<a.length; i++) System.out.println(i + ": " + a[i]); 0: 0 1: 1 2: 4 3: 9 4: 16
Array "literals": {expression, ..., expression}
bsh % String[] charCodes = new String[] {"A: " + (int)'A', "B: " + (int)'B', "C: " + (int)'C'}; bsh % print(charCodes.length); 3 bsh % for (int i=0; i<charCodes.length; i++) print(charCodes[i]); A: 65 B: 66 C: 67
Some tests motivated by class discussion:
bsh % int[] a; bsh % print(a.length); // Error: bsh.EvalError: Null pointer error... : bsh % a = new int[0]; bsh % print(a.length); 0 bsh % a[0] = 3; // Error: bsh.EvalError: Assignment: Array access:java.lang.ArrayIndexOutOfBoundsException :
See Histogram example.
Two Dimensional Arrays
Declaration: type[][] _array;
for any type
.
_array;
is an array of arrays of type
type
.
bsh % int[][] d2a = new int[5][10]; bsh % print(d2a.length); 5 bsh % print(d2a[2].length); 10 bsh % int[][] d2a = new int[5][10]; bsh % for (int i=0; i<d2a.length; i++) for (int j=0; j<d2a[i].length; j++) d2a[i][j] = i*j; bsh % for (int i=0; i<d2a.length; i++) for (int j=0; j<d2a[i].length; j++) System.out.println(i + "," + j + ": " + d2a[i][j]); 0,0: 0 0,1: 0 0,2: 0 0,3: 0 0,4: 0 0,5: 0 0,6: 0 0,7: 0 0,8: 0 0,9: 0 1,0: 0 1,1: 1 1,2: 2 1,3: 3 1,4: 4 1,5: 5 1,6: 6 1,7: 7 1,8: 8 1,9: 9 2,0: 0 2,1: 2 2,2: 4 2,3: 6 2,4: 8 2,5: 10 2,6: 12 2,7: 14 2,8: 16 2,9: 18 3,0: 0 3,1: 3 3,2: 6 3,3: 9 3,4: 12 3,5: 15 3,6: 18 3,7: 21 3,8: 24 3,9: 27 4,0: 0 4,1: 4 4,2: 8 4,3: 12 4,4: 16 4,5: 20 4,6: 24 4,7: 28 4,8: 32 4,9: 36
See Checker Board example.