1

I'm writing an app for Android. I use a string array to pull all player names from shared preferences (has to be a string array). I have a list to pull all active players from shared preferences (has to be a list). I need to check my list to see if it contains any players that are not in my player's array and delete them. I just can't seem to figure out the logic.

For example:

List contains: b c a e

Array contains: a b c d

Since 'e' exists in List but not in Array, 'e' needs to be removed from the list. I know the commands (.contains(), .remove(), for()), I just can't figure out the logic.

My first attempt was:

for(int x=0;x<numOfPlayers;x++){
        players[x] = getPrefs.getString("player"+Integer.toString(x), " ");
        if(activePlayers.size()>0)
            if(activePlayers.contains(players[x]))
                playersChecked[x] = true;
        else{
            if(x<activePlayers.size())
                activePlayers.remove(x);
        }
    }

But this removes x from activePlayers if player[x] has an item that activePlayers doesn't, which is fine. It needs to be the other way around.

2 Answers 2

11

What you're looking for is Collection.retainAll.

Retains only the elements in this collection that are contained in the specified collection

list.retainAll(Arrays.asList(array));
Sign up to request clarification or add additional context in comments.

Comments

1

One important point that will make your life difficult, your method is going to have unwanted consequences. Removing a player is going to change the elements in the list, so that you will end up skipping over players.

For example, in the list:

{ A, B, C }

if you remove B, you end up with:

{ A, C }

When x increments, you end up with x = 3, which used to point at C. But now it points at nothing.

Instead, look into using an iterator. See: Iterator in Java

That will allow you to remove elements without mucking up your index.

So to answer your question, I would create an iterator over activePlayers. As you iterate, simply check each item in the iterator against the list, and remove the item if is not found.

3 Comments

Probably a better idea to add the array elements to a Set which is more suited for contains.
Welcome to StackOverflow, Jay.
Thanks, owlstead. I've been enjoying the benefits for years, thought it was time to give back.

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.