Java Reference
In-Depth Information
double[] data = new double[100];
fill(data, 5, 11, 1.5);
This specifies that a range of elements in the array are to be set to a given value. You supply four argu-
ments to this version of the fill() method. The first argument is the name of the array, data . The second
argument is the index of the first element to be set. The third argument is 1 beyond the index of the last
element to be set. The fourth argument is the value for the elements. This sets all the elements from data[5]
to data[10] inclusive to 1.5.
There are versions of the fill() method for each of the primitive element types so you can use it to set
values for any array of elements of a primitive type.
Initializing an Array Variable
You can initialize an array variable with a reference to an existing array of the same type. For example, you
could declare the following array variables:
long[] even = {2L, 4L, 6L, 8L, 10L};
long[] value = even;
Here the array reference stored in even is used to initialize the array value in its declaration. This has the
effect shown in Figure 4-3 .
FIGURE 4-3
You have created two array variables, but you have only one array. Both arrays refer to the same set
of elements, and you can access the elements of the array through either variable name — for example,
even[2] refers to the same variable as value[2] . One use for this is when you want to switch the arrays
referenced by two variables. If you were sorting an array by repeatedly transferring elements from one array
to another, by flipping the array you were copying from with the array you were copying to, you could use
the same code. For example, if you declared array variables as
double[] inputArray = new double[100]; // Array to be sorted
double[] outputArray = new double[100]; // Reordered array
double[] temp; // Temporary array reference
when you want to switch the array referenced by outputArray to be the new input array, you could write
the following:
 
 
Search WWH ::




Custom Search