0

I have managed to get myself into a situation where I cant re-use arrayList elements in my game.

Now I am wondering, is it much more expensive to remove the element and then create a new one compared to using the same 10 elements and just swapping their positions, giving the illusion that they get removed?

Ex:

arrayList.remove(i)
arrayList.add(New Object(image, x, y));
WEDEBE
  • 148
  • 1
  • 9
  • 1
    In Java you cannot remove array elements; all arrays are fixed size. Are you speaking about `ArrayList`? Also your code does not compile in Java. Please provide real code snippet. – Tagir Valeev May 03 '15 at 05:02
  • @TagirValeev no he has `array.remove` and `array.add` but he's talking about regular arrays, also why does he need to provide more code? his question is clear – Abdul Ahmad May 03 '15 at 05:03
  • here's something that will give you some more insight, and lead you in the right direction: http://stackoverflow.com/questions/4938626/moving-items-around-in-an-arraylist – Abdul Ahmad May 03 '15 at 05:07
  • If the element you are removing from an array is not the one with the highest index, the others with higher indexes will have to slid into place. Also, if the array is bound to a UI element, there might be events fired off with removal and re-indexing. Modifying the contents in place might be faster than removing and inserting, particularly if it's not the last element. – ostrichchasedwormaroundfield May 03 '15 at 05:11
  • The code above is more pseudocode than anything, and yes, I mean arrayList, that is my bad, will edit!. – WEDEBE May 03 '15 at 05:17

1 Answers1

1

It depends

Insertion/deletion at the beginning of the array cost O(n), if array is not full due to shifting of the elements. For arraylist its O(n)

Insertion at the end cost O(1) if array is not full. For arraylist O(1) if array is not full and O(n) if array is full

deletion at the end cost O(1). For arraylist O(n)

Insertion/deletion at the middle cost O(n) if array is not full due to shifting of the elements. For arraylist O(n)

sol4me
  • 15,233
  • 5
  • 34
  • 34