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?

5
  • 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. Commented Apr 17, 2016 at 20:41
  • 1
    You could store the elements in a Map<Integer, Player>; then you can remove arbitrary elements (and keys) without effecting other keys. Commented Apr 17, 2016 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? Commented Apr 17, 2016 at 20:45
  • Possible duplicate of Java, Using Iterator to search an ArrayList and delete matching objects Commented Apr 17, 2016 at 20:50
  • i believe your best choice is to use a map as @ElliottFrisch said Commented Apr 17, 2016 at 20:53

1 Answer 1

6

Instead of using

players.remove(thisPlayer);

You could try something along the lines of

players.set(players.indexOf(thisPlayer),null);
Sign up to request clarification or add additional context in comments.

1 Comment

my idea was very similary to this, just instead of null, I'd put some dummy player or something

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.