Vulcan
Vulcan

Reputation: 307

Reinitialize all array elements to zero java

I have a 2-D array which needs to be reinitialized to 0 after every iteration what is the best (fastest) method to do so.

PS- I need it for optimization in Coding Competitions.

Upvotes: 0

Views: 2987

Answers (2)

Sam Estep
Sam Estep

Reputation: 13304

You could use the Arrays.fill function:

for (long[] subarray : myarray) {
  Arrays.fill(subarray, 0);
}

Upvotes: 2

M A
M A

Reputation: 72844

FYI, you don't need to explicity set all elements to zero. myarray=new long[size][size] will fill default values of zero in the elements. See Initial Values of Variables:

Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10.2):

  • For type byte, the default value is zero, that is, the value of (byte)0.

  • For type short, the default value is zero, that is, the value of (short)0.

  • For type int, the default value is zero, that is, 0.

  • For type long, the default value is zero, that is, 0L.

If the size is big though, it's more efficient to set the values:

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

Upvotes: 1

Related Questions