Reputation: 7380
I have a bidimensional Object array in Java. Some indices aren´t used, because they were skipped during array fill. The array looks like this:
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"?
Upvotes: 1
Views: 1357
Reputation: 272297
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).
Upvotes: 2