• Create Account

### #ActualBacterius

Posted 15 September 2012 - 08:28 PM

Does order need to be conserved in the array? Because if not, you can simply swap the element to delete with the last element in the array, and cut the last element off (by resizing the array or doing an arraycopy on a new array). This is really efficient but if your array was sorted for instance it will no longer be.

If the order has to be preserved, you want to set the element to delete to null, and bring every element after that down a notch, and then resize the array by one less element (or again, just arraycopy, which is more efficient at this point since block memory copy is faster than walking through the array, but if you have a lot of elements to delete or if you need to go through the array to find which ones to delete, you may be better off sweeping through the array backwards and pushing everything down as needed).

So if you need to delete element at position P in an array of N elements, you would create a new array of N - 1 elements, and:
- arraycopy the first P - 1 elements of the old array into the beginning of the new array
- arraycopy the elements from index P + 1 to N - 1 of the old array into the new array at index P
(assuming zero-based indices)

### #1Bacterius

Posted 15 September 2012 - 08:26 PM

Does order need to be conserved in the array? Because if not, you can simply swap the element to delete with the last element in the array, and cut the last element off (by resizing the array or doing an arraycopy on a new array). This is really efficient but if your array was sorted for instance it will no longer be.

If the order has to be preserved, you want to set the element to delete to null, and bring every element after that down a notch, and then resize the array by one less element (or again, just arraycopy, which is more efficient at this point since block memory copy is faster than walking through the array, but if you have a lot of elements to delete or if you need to go through the array to find which ones to delete, you may be better off sweeping through the array backwards and pushing everything down as needed).

PARTNERS