9

Possible Duplicate:
Any shortcut to initialize all array elements to zero?

How to Initializing a normal 2D array with zeros(all shells should have zero stored) without using that old looping method that takes lots of time .My code wants something that should take very less time but via looping method my time limit exceeds.

Community
  • 1
  • 1
rick
  • 913
  • 6
  • 13
  • 28
  • 13
    `int[][] a = new int[20][10];` Isn't that working for you? – Marko Topolnik Jul 23 '12 at 08:49
  • yes its working but i want to Initializing my array with zero – rick Jul 23 '12 at 08:51
  • 2
    Check it out - after Marko's code, it will be "all zeros" – tucuxi Jul 23 '12 at 08:51
  • 3
    Java always gives you an object full of zeros, null or false. You never have to worry about zeroing out an object. – Peter Lawrey Jul 23 '12 at 08:54
  • This question has been asked and answered before. See [Any shortcut to initialize all array elements to 0?](http://stackoverflow.com/questions/2154251/any-shortcut-to-initialize-all-array-elements-to-zero "Any shortcut to initialize all array elements to 0?") – Wes Jul 23 '12 at 08:51

1 Answers1

13

The important thing to realise here is that if you're storing primitives then the default value is zero (scroll down to the Default Values section). This applies to array initialisation as well as simple variable initialisation, and consequently you don't have to initialise the array contents explicitly to zero.

If you have to reset an existing structure, however, then you'd have to loop through the structure, and you may be better off initialising a new instance of your array structure.

Note that if you're creating an array or arrays, obviously you have to initialise the first array with the contained array.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • yes i wanted to reset my array...thanks for the solution – rick Jul 23 '12 at 08:56
  • @rick: Be careful reassigning the arrays. You'll buy yourself time here, but get hit with much more garbage collection. Need to see which one is best for your particular situation. – Liron Jul 23 '12 at 08:58