Re: Quick way to initialize array with all zeros




"Andrew Thompson" <andrewthommo@xxxxxxxxx> wrote in message
news:1175351325.841838.96100@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
On Mar 31, 11:59 pm, Patricia Shanahan <p...@xxxxxxx> wrote:
001 wrote:
I want to initialize a large array with 0's... do I have to use a
for-loop
or is there some trick to accomplish this?

new int[n] is an all zero int array of size n. If you have an existing
array and need to reinitialize it to zero, use Arrays.fill.

I 'object' to such simplistic answers to what is
effectively a complex question. My first question
for the OP would be, what do you mean by 'quick'?

There are two potential meanings, AFAIU.
1) quick to code.
2) quick to run.

The first is inconsequential, the only point
to writing a shorter method is for the purposes
of code clarity (which has little to do with
'quick').

And for the second, I am not convinced that
Arrays.fill() takes less CPU cycles.

Here is the test code/results I am seeing..
<sscce>
import java.util.Arrays;

class InitialiseToZero {

public static void main(String[] args) {
int length = 10000001;
int[] intArray = new int[length];
long startTimeOfLoop = System.currentTimeMillis();
for (int ii=0; ii<length; ii++) {
intArray[ii] = 1;
}
long endTimeOfLoop = System.currentTimeMillis();

long startTimeOfFill = System.currentTimeMillis();
Arrays.fill( intArray, 0 );
long endTimeOfFill = System.currentTimeMillis();

System.out.println( "Time to loop " +
(endTimeOfLoop - startTimeOfLoop) );
System.out.println( "Time to fill " +
(endTimeOfFill - startTimeOfFill) );
}
}
</sscce>

Why did you fill the int array with 1's in the for loop test
and 0's in the Arrays.fill test?

George


.