Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
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
Array
classset
andget
methods to access array elements when the name of the array is unknown at compile time. In addition toget
andset
, theArray
class has specialized methods that work with specific primitive types. For example, the value parameter ofsetInt
is anint
, and the object returned bygetBoolean
is a wrapper for aboolean
type.The sample program that follows uses the
set
andget
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
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.