Question

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?

Was it helpful?

Solution 3

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.

OTHER TIPS

You should use set(int index, E element) method of ArrayList.

Acc. to Javadocs:

Replaces the element at the specified position in this list with the specified element

If you want to remove an item from an ArrayList and still want the rest of the list to keep in place, simply replace it with null, that's authorized :

myList.set(i, null);

Of course that means you'll have to test the value when using it.

Use a Tile object with an enum to store its state:

public class Tile {

  public enum State = { WALL, OPEN };

  private State state;

  public void setState(State state) {
    this.state = state;
  }
}

When you need to swap between open space and wall, you just change its state:

tile.setState(State.WALL);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top