Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Arrays.fill()

Tags:

How to fill a multidimensional array?

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

I tried it, but it doesn't work.

like image 997
alphachap Avatar asked Mar 09 '11 21:03

alphachap


People also ask

What is arrays fill in Java?

fill() method is in java. util. Arrays class. This method assigns the specified data type value to each element of the specified range of the specified array.

How do you fill an element in an array in Java?

Solution. This example fill (initialize all the elements of the array in one short) an array by using Array. fill(arrayname,value) method and Array. fill(arrayname, starting index, ending index, value) method of Java Util class.

How do you fill an array with a double in Java?

fill(double[] a, int fromIndex, int toIndex, double val) method assigns the specified double value to each element of the specified range of the specified array of doubles. The range to be filled extends from index fromIndex, inclusive, to index toIndex, exclusive.

How do you fill an array with arrays?

Using the fill() method The fill() method, fills the elements of an array with a static value from the specified start position to the specified end position. If no start or end positions are specified, the whole array is filled. One thing to keep in mind is that this method modifies the original/given array.


2 Answers

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 :-)

like image 173
aioobe Avatar answered Sep 21 '22 11:09

aioobe


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.

like image 23
Argote Avatar answered Sep 20 '22 11:09

Argote