Java Reference
In-Depth Information
The first statement declares and defines an integer array of 100 elements, all of which are initialized to
zero by default. The two assignment statements then set values for the first two array elements.
You can also initialize the elements in an array using a for loop to iterate over all the elements and set
the value for each:
double[] data = new double[50]; // An array of 50 values of type double
for(int i = 0 ; i < data.length ; ++i) { // i from 0 to data.length-1
data[i] = 1.0;
}
For an array with length elements, the index values for the elements run from 0 to length-1 . The for
loop control statement is written so that the loop variable i starts at 0 and is incremented by 1 on each itera-
tion up to data.length-1 . When i is incremented to data.length , the loop ends. Thus, this loop sets each
element of the array to 1. Using a for loop in this way is one standard idiom for iterating over the elements
in an array. You see later that you can use the collection-based for loop for iterating over and accessing
the values of the array elements. Here you are setting the values so the collection-based for loop cannot be
applied.
Using a Utility Method to Initialize an Array
You can also use a method that is defined in the Arrays class in the java.util package to initialize an array.
For example, to initialize the data array defined as in the previous fragment, you could use the following
statement:
Arrays.fill(data, 1.0); // Fill all elements of data with 1.0
The first argument to the fill() method is the name of the array to be filled. The second argument is the
value to be used to set the elements. This method works for arrays of any primitive type. Of course, for this
statement to compile correctly you need an import statement at the beginning of the source file:
import java.util.Arrays;
This statement imports the Arrays class name into the source file so you can use it as you have in the
preceding code line. Without the import statement, you can still access the Arrays class using the fully
qualified name. In this case the statement to initialize the array is:
java.util.Arrays.fill(data, 1.0); // Fill all elements of data with 1.0
This is just as good as the previous version of the statement.
Of course, because fill() is a static method in the Arrays class, you could import the method name into
your source file:
import static java.util.Arrays.fill;
Now you can call the method with the name unadorned with the class name:
fill(data, 1.0); // Fill all elements of data with 1.0
You can also set part of an array to a particular value with another version of the fill() method:
Search WWH ::




Custom Search