Reputation: 307
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.
Or assign memory to it again by doing myarray=new long[size][size];
long myarray[][]=new long[size][size]
for(.....)
{
//..do something with myarray
//..set all elements of myarray to 0 for next iteration
}
PS- I need it for optimization in Coding Competitions.
Upvotes: 0
Views: 2987
Reputation: 13304
You could use the Arrays.fill
function:
for (long[] subarray : myarray) {
Arrays.fill(subarray, 0);
}
Upvotes: 2
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