Search code examples
javaarraylisttiles-game

Removing data safely from an arraylist


I have an array list that contains tiles in it. When I place a new tile down, the new tile is placed over the old one, but the old one is still there and can cause problems. For example, there is a stone tile that the player cannot walk through. An air tile is placed there, supposedly letting the player walk through. However, the stone tile is never deleted, so the player cannot walk through since the stone tile is solid and causes collision. Can I just delete the tile out of the arraylist? I don't think I can because then the rest of the data in the list will "move over" and fill the hole where the old tile used to be. How could I remove the tile and place a new tile over it without causing the rest of the data to shift?


Solution

  • You can use the set() method of the ArrayList to "replace" one object in the list with another.

          tileList.set(index, newTileObject);
    

    will replace the tile at index with the new tile object. Leaving all the other tiles in their original location in the list.