Arrays.Fill with Multidimensional Array in Java

Can I use Arrays.fill with a 2d array? If so how do I do that?

No, it doesn't work.

However, all is not lost! You don't even need to have the nested loop. Just do this:

public void FillArray(String[][] SC){
for (int i = 0; i < SC.length; i++){
Arrays.fill(SC[i], "-");
}
}

Using a loop is how you can fill each of the inner arrays separately, but Arrays.fill handles the inner loop for you.

Filling a multidimensional array in Java using enhanced for loop

The first method does not fill the array, because in the code

for (char column : rows) {
column = '*';
}

the value in the array is copied to the new variable column. You then just assign a new value for this variable, but the element in the array remains unchanged.

The method Arrays.fill() does not copy the value, instead it operates directly on the array. You can do so yourself with this code (which is basically the same as Arrays.fill() does):

for (int i = 0; i < battleBoard.length; i++) {
for (int j = 0; j < battleBoard[i].length; j++) {
battleBoard[i][j] = '*';
}
}

Filling a Multidimensional Array using a Stream

Here you have a solution that produces the array instead of modifying a previously defined variable:

String[][] array = 
IntStream.range(0, 3)
.mapToObj(x -> IntStream.range(0, 3)
.mapToObj(y -> String.format("%c%c", letter(x), letter(y)))
.toArray(String[]::new))
.toArray(String[][]::new);

If you want to use parallel streams then it's very important to avoid side effects like modifications of a variable (array or object). It might lead to race conditions or other concurrency issues. You can read more about that in java.util.stream package documentation - see Non-interference, Stateless behaviors and Side-effects sections.

How to initialize all the elements of a 2D array to any specific value in java

The Arrays.fill() method can be used to fill a 1-d array, but there's no built in method to do a "deep" fill of multi-dimensional arrays.

For 2-d arrays I do something like this:

int[][] arr2 = new int[5][5];  
for(int[] arr1 : arr2)
Arrays.fill(arr1, 1);

Java's Arrays.fill() with multidimensional array

if you look at the source code (which is copied below) for Arrays.fill() you will find that its only a for loop.

public static void fill(int[] a, int fromIndex, int toIndex, int val) {
rangeCheck(a.length, fromIndex, toIndex);
for (int i=fromIndex; i<toIndex; i++)
a[i] = val;
}

So writing a for loop to fill the columns of the array would be the same sort of code that Arrays.fill() is giving you.



Related Topics



Leave a reply



Submit