Java Reference
In-Depth Information
Here's how you could fill an array of integers with a particular value:
long[] values = new long[1000];
java.util.Arrays.fill(values, 888L); // Every element as 888
It's quite easy to initialize multidimensional arrays, too. To initialize a two-dimensional array, for ex-
ample, you treat it as an array of one-dimensional arrays. For example:
int[][] dataValues = new int[10][20];
for(int[] row : dataValues) {
Arrays.fill(row, 99);
}
The
for
loop sets every element on the
dataValues
array to 99. The loop iterates over the 10 arrays of
20 elements that make up the
dataValues
array. If you want to set the rows in the array to different values,
you could do it like this:
int initial = 0;
int[][] dataValues = new int[10][20];
for(int[] row : dataValues) {
Arrays.fill(row, ++initial);
}
This results in the first row of 20 elements being set to 1, the second row of 20 elements to 2, and so on
through to the last row of 20 elements that is set to 10.
The version of
fill()
that accepts an argument of type
Object[]
obviously processes an array of any
class type. You could fill an array of
Person
objects like this:
Person[] people = new Person[100];
java.util.Arrays.fill(people, new Person("John", "Doe"));
This inserts a reference to the object passed as the second argument to the
fill()
method in every ele-
ment of the
people
array. Note that there is only one
Person
object that all the array elements reference.
Another version of
fill()
accepts four arguments. This is of the form:
fill(
type
[] array, int fromIndex, int toIndex,
type
value)
This fills part of
array
with
value,
starting at
array[fromIndex]
up to and including
ar-
ray[toIndex-1]
. There are versions of this method for the same range of types as the previous set of
fill()
methods. This variety of
fill()
throws an
IllegalArgumentException
if
fromIndex
is greater
than
toIndex
. It also throws an
ArrayIndexOutOfBoundsException
if
fromIndex
is negative or
toIndex
is greater than
array.length
. Here's an example of using this form of the
fill()
method:
Person[] people = new Person[100];
java.util.Arrays.fill(people, 0, 50, new Person("Jane", "Doe"));
java.util.Arrays.fill(people, 50, 100, new Person("John", "Doe"));