tags:

views:

188

answers:

3

Hi,

I have a bidimensional Object array in Java. Some indices aren´t nor used, because thei were skipped during array fill. Array looks like:

Array[0][0]
Array[0][1]
Array[0][2]
Array[1][0]
Array[1][1]
Array[1][2]
Array[3][0]
Array[3][1]
Array[3][2]

The 2 is missing, how can i rebuild the indices to make the array "correct"?

+2  A: 

If you have an element (or set of elements) that aren't populated, you just provide in the missing value(s) using:

Array[2] = new Object[3];

or are you looking to compress the array ? If the latter, just create a new array

Object[] NewArray = new Object[Array.length-1];

and iterate through Array, skipping the null value.

int j = 0;
for (int i = 0; i < Array.length; i++) {
   if (Array[i] != null) {
      NewArray[j++]=Array[i];
   }
}

Unfortunately you can't resize an array once it's created (use an ArrayList if you want more dynamic behaviour).

Brian Agnew
+2  A: 

Arrays elements cannot be "missing", I assume you have code to print the array, please could you show us the code?

djna
+1  A: 

Hmm, did you think about:

array[2] = array[3];
array[3] = null;
Mnementh
The problem is you still have the 'missing' value - it's now just at the end.
Brian Agnew
Then a new array is needed and copying the 'filled' values to the new array. You showed this in your answer already.
Mnementh