Arrays 1D, 2D
Arrays 1D, 2D
James Brucker
Arrays
An array is a series of elements of the same type, which
occupy consecutive memory locations.
float[] x = new float[10]; // array of 10 float vars
char[] c = new char[40]; // array of 40 char vars
Don't forget -1 !
int[]
length=10
You can initialize array elements 0
any way you like. 1
2
Some examples in later slides. ...
Short-cut to create an Array
You can combine steps (1) and (2) into one statement:
<<memory>>
int[] p = new int[10]; p <object>
Demo in class.
Arrays.sort( words );
Output:
0: ANT
1: DOGS
2: cat
3: dog
4: frog
An Array of Fibonacci Numbers
This example shows how to process all elements of an array.
The important point is that the "for" loop starts at k=0 and tests
k < fib.length (false when k=fib.length)
int [] b = { 0, 0, 0 }; int[]
length=4
b = a; // Does what? 2
b[2] = 999; 4
6
System.out.println(a[2]); 8
System.out.println(
int[]
"b.length=" + b.length ); length=3
0
0
0
"b = a" copies the reference, not the array
<<memory>>
b = a;
a <object>
makes b refer to same array as a.
b <object>
b = a; int[]
length=4
b[2] = 999;
2
System.out.println(a[2]); 4
999
System.out.println( 8
"b.length=" + b.length );
int[]
length=3
0
0
0
The result:
<<memory>>
b = a;
a <object>
b[2] = 999;
System.out.println(a[2]); b <object>
System.out.println( int[]
length=4
"b.length=" + b.length );
2
4
6
999 8
b.length = 4
int[]
length=3
0
0
0
How do you really copy an array?
Here is one solution:
int[] a = { 2, 4, 6, 8 };
// java.util.Arrays.copyOf( ... )
// creates a new array for copy.
int[] b = Arrays.copyOf( a, a.length );
int [] array = { 2, 4, 6, 8, 10 };