codeofnode
codeofnode

Reputation: 18609

How to autofill an array in java..?

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..?

Upvotes: 0

Views: 6423

Answers (4)

Denys Séguret
Denys Séguret

Reputation: 382122

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.

Upvotes: 4

akuhn
akuhn

Reputation: 27793

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.

Upvotes: 1

Parth Soni
Parth Soni

Reputation: 11648

Use Arrays.fill()

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

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213223

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);
}

Upvotes: 1

Related Questions