alphachap
alphachap

Reputation: 201

Java Arrays.fill()

How to fill a multidimensional array?

int[][] array = new int[4][6]; 
Arrays.fill(array, 0);

I tried it, but it doesn't work.

Upvotes: 20

Views: 49844

Answers (5)

GreMal
GreMal

Reputation: 321

See this way:

Arrays.fill(array[0], 0);
Arrays.fill(array, array[0]);

Upvotes: -3

Paŭlo Ebermann
Paŭlo Ebermann

Reputation: 74750

First, note that 0 is the default value for int arrays, so you don't have to fill something with 0.

If you want your array to stay truly multidimensional, you'll need a loop.

public static void fill(int[][] array, int element) {
    for(int[] subarray : array) {
        Arrays.fill(subarray, element);
    }
}

If you only need a 2D-array filled with the same element and don't want to change the subarrays later, you can use this trick:

public static int[][] create2DArray(int length, int subLength, int element) {
    int[] subArray = new int[subLength];
    Arrays.fill(subArray, element);
    int[][] array = new int[length][];
    Arrays.fill(array, subArray);
    return array;
}

This works analogously for higher-dimensional arrays.

Upvotes: 1

aioobe
aioobe

Reputation: 420951

Here's a suggestion using a for-each:

for (int[] row : array)
    Arrays.fill(row, 0);

You can verify that it works by doing

System.out.println(Arrays.deepToString(array));

A side note: Since you're creating the array, right before the fill, the fill is actually not needed (as long as you really want zeros in it). Java initializes all array-elements to their corresponding default values, and for int it is 0 :-)

Upvotes: 31

duffymo
duffymo

Reputation: 308753

Since array is really an array of arrays, perhaps you can try looping over each row and doing fill for each one individually.

Upvotes: 2

Argote
Argote

Reputation: 2155

Try this:

for(int i = 0; i < array.length; i++) {
    Arrays.fill(array[i], 0);
}

I haven't tested it but I think it should work.

Upvotes: 13

Related Questions