Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a 2D-array with zero in JAVA [duplicate]

Tags:

java

arrays

time

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.

like image 527
rick Avatar asked Jul 23 '12 08:07

rick


People also ask

How do you create a duplicate 2D array in Java?

A simple solution is to use the clone() method to clone a 2-dimensional array in Java. The following solution uses a for loop to iterate over each row of the original array and then calls the clone() method to copy each row.

How do you initialize a 2D array to 0?

int array [ROW][COLUMN] = {0}; which means: "initialize the very first column in the first row to 0, and all other items as if they had static storage duration, ie set them to zero." int array [ROW][COLUMN] = {1}; it means "initialize the very first column in the first row to 1 and set all other items to zero".

How do you find duplicates in a 2D array in Java?

Here's a brute-force straight forward way of counting duplicates. Turn the 2d array into a 1d array ( List<Integer> ), then loop through the 1d array counting the duplicates as you find them and removing them so you don't count them more than once.


1 Answers

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.

like image 172
Brian Agnew Avatar answered Sep 23 '22 19:09

Brian Agnew