Java Reference
In-Depth Information
You can also initialize an array with an existing array. For example, you could declare the following
array variables:
long[] even = {2L, 4L, 6L, 8L, 10L};
long[] value = even;
where the array even is used to initialize the array value in its declaration. This has the effect shown below.
You have created two array variables, but you only have 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 we 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 we want to switch the array referenced by outputArray to be the new input array, we could write:
temp = inputArray; // Save reference to inputArray in temp
inputArray = outputArray; // Set inputArray to refer to outputArray
outputArray = temp; // Set outputArray to refer to what was inputArray
None of the array elements are moved here. Just the addresses of where the arrays are located in
memory are swapped, so this is a very fast process. Of course, if you want to replicate an array, you
have to define a new array of the same size and type, and then copy each element of the array
individually to your new array.
Using Arrays
You can use array elements in expressions in exactly the same way as you might use a single variable of
the same data type. For example, if you declare an array samples , you can fill it with random values
between 0.0 and 100.0 with the following code:
Search WWH ::




Custom Search