|
|
Working with Arrays |
In most programs, to access array elements you merely use an assignment expression as follows:This technique will not work if you don't know the name of the array until runtime.int[10] codes; codes[3] = 22; aValue = codes[3];Fortunately, you can use the
Arrayclasssetandgetmethods to access array elements when the name of the array is unknown at compile time. In addition togetandset, theArrayclass has specialized methods that work with specific primitive types. For example, the value parameter ofsetIntis anint, and the object returned bygetBooleanis a wrapper for abooleantype.The sample program that follows uses the
setandgetmethods 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
|
|
Working with Arrays |