In most programs, to access array elements you merely use an assignment expression:
The sample program that follows uses the
This technique will not work if you don't know the name of the array until run time. Fortunately, you can use theint[10] codes;
codes[3] = 22;
aValue = codes[3];
Array
class set
and get
methods to access array elements when the name of the array is unknown at compile time. In addition to get
and set
, the Array
class has specialized methods that work with specific primitive types. For example, the value parameter of setInt
is an int
, and the object returned by getBoolean
is a wrapper for a boolean
type. The sample program that follows uses the
set
and get
methods to copy the contents of one array to another. The output of the sample program is:import java.lang.reflect.*;
class SampleGetArray {
public static void main(String[] args) {
int[] sourceInts = {12, 78};
int[] destInts = new int[2];
copyArray(sourceInts, destInts);
String[] sourceStrgs = {"Hello ", "there ", "everybody"};
String[] destStrgs = new String[3];
copyArray(sourceStrgs, destStrgs);
}
public static void copyArray(Object source, Object dest) {
for (int i = 0; i < Array.getLength(source); i++) {
Array.set(dest, i, Array.get(source, i));
System.out.println(Array.get(dest, i));
}
}
}
12
78
Hello
there
everybody
No comments:
Post a Comment