rphello101
rphello101

Reputation: 1771

How to compare a list and string array (Java)?

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.

Upvotes: 1

Views: 3358

Answers (2)

Jay Bobzin
Jay Bobzin

Reputation: 1020

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.

Upvotes: 1

obataku
obataku

Reputation: 29636

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));

Upvotes: 11

Related Questions