1

So i need to delete a specific object under the index number of how many times my loop has passed in an arraylist.

lets say i want to delete my object that has an index 0 on arraylist

but the object on index 1 and index 2 (and so on) still need to be the same index number as before i removed index 0.

        for (int i = 0; i < 4 i++) {
            player thisPlayer = players.get(i);

            if (not important) {
                players.remove(thisPlayer);
            }
        }

if player 1 needs to be removed, the other players need to maintain the same index.

what do i do?

Stefan Dollase
  • 4,530
  • 3
  • 27
  • 51
Zagyax
  • 29
  • 1
  • 3
  • 1
    You could set the value at that element to `null`. Removing elements, except when removing from the end, will shift other elements forward, as you probably know. – Logan Apr 17 '16 at 20:41
  • 1
    You could store the elements in a `Map`; then you can remove arbitrary elements (and keys) without effecting other keys. – Elliott Frisch Apr 17 '16 at 20:44
  • Is it actually important that the index remains unchanged **after** the loop is finished, or is it just important to make the loop work? – Stefan Dollase Apr 17 '16 at 20:45
  • Possible duplicate of [Java, Using Iterator to search an ArrayList and delete matching objects](http://stackoverflow.com/questions/8174964/java-using-iterator-to-search-an-arraylist-and-delete-matching-objects) – Stefan Dollase Apr 17 '16 at 20:50
  • i believe your best choice is to use a map as @ElliottFrisch said – Abdullah Asendar Apr 17 '16 at 20:53

1 Answers1

6

Instead of using

players.remove(thisPlayer);

You could try something along the lines of

players.set(players.indexOf(thisPlayer),null);
Jon
  • 91
  • 2
  • my idea was very similary to this, just instead of null, I'd put some dummy player or something – Vucko Apr 17 '16 at 21:57