0

How can i autofill an array (specially multidimensional) in java with '-1' without using any loops..?

I know by default java initialize all the elements of array with '0'. But what if i want to replace all zeroes with -1 at once..! Without using any loop.

Is there any shortcut available..?

4 Answers 4

4

You can use Arrays.fill to fill a one dimensional array but you'll have to loop for multi-dimensional arrays.

    int[][] array = new int[100][100];
    for (int[]a : array) {
        Arrays.fill(a, -1);
    }

What's your reason to avoid loops ? If you're concerned with performances (and you're sure there is a problem) you might do what is often done, that is flatten your array in a one-dimensional one :

 int[] flatarray = new int[width*height];

then you can fill it with only one fill (which hides a loop, though) and many manipulations would be a little more efficient. Accessing a cell would be flatarray[x+y*width].But you should profile first to ensure you need this.

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

Comments

1

You can use Arrays.fill method to fill single dimensional array: -

int[] array = new int[5];
Arrays.fill(array, -1);

To fill 2-dimensional array, you can apply the above method to each single dimensional array by iterating.

int[][] multiArr = new int[10][10];
for (int[] innerArr: multiArr) {
    Arrays.fill(innerArr, -1);
}

Comments

1

Use Arrays.fill()

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

Comments

1

For one dimensional array you can use

int[] array = new int[9000];
Arrays.fill(array, -1)

but for multidimensional array you will have to use a loop.

Your requirement of not using a loop sounds rather arbitrary, because in fact even in the case of a one dimensional array you are using a loop. It is just hidden away in the fill method. At a technical level there is no way of filling a data structure without looping over it!

 

You best learn to stop worrying and love the for loop.

Comments

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.