0

In Java, we can fill 1 dimensional Integer array with using

Arrays.fill(arr, -1);

Is there any way to fill 2 or 3 dimensional Integer array without using loop? With using 1 loop or 2 loop I can. But I want to know how can I fill without using this.

5
  • 2
    why do you want to do this? Anyway Arrays.fill() is using simple for loop so you will get no performance boost here. Just create your own method Commented Dec 2, 2018 at 13:00
  • 1
    In fact Arrays#fill also uses a loop internally. So you never fill an array without a loop. Commented Dec 2, 2018 at 13:02
  • If you are going to fill a multi-dimensional array, you are not going to have a sparse or triangular array anyway, so you could just use a one-dimensional array instead and fiddle with the indexes a bit to make it look multi-dimensional. Commented Dec 2, 2018 at 13:07
  • Thanks for all comments. I know that Arrays.fill use simple for loop. but i just want to know if there is any way to fill without "showing loop" which means that be shown on the code. Commented Dec 2, 2018 at 13:09
  • This is silly. But you can replace loops with recursion. Commented Dec 2, 2018 at 13:09

1 Answer 1

1

Have you tried

Arrays.fill(row, -1);
Arrays.fill(arr, row);

you should get:

[
 [-1,-1,-1],
 [-1,-1,-1],
 [-1,-1,-1]
]

Complete example:

import java.util.Arrays;

public class Fill {

    public static void main(String[] args) {
        int[] row = new int[5];
        int[][] arr = new int[5][];
        Arrays.fill(row, -1);
        Arrays.fill(arr, row);

        for (int[] r : arr) {
            for (int c : r) {
                System.out.print(c + "  ");
            }
            System.out.println();
        }

    }
}

Please note, this way, you'll get an array of references to the same initial array

Sign up to request clarification or add additional context in comments.

4 Comments

But that will put the same single row into every column. Meaning if you change one element, it will update in lots of different places.
That's what was asked - how to fill an array with the same value Is there any way to fill 2 or 3 dimensional Integer array without using loop?
yes, with the same values, not with references to a single shared value.
@Thilo you are right you'd have an array of references pointing to the same initial array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.