[英]How to compare a list and string array (Java)?
I'm writing an app for Android. 我正在为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: bcae 列表包含:bcae
Array contains: abcd 数组包含:abcd
Since 'e' exists in List but not in Array, 'e' needs to be removed from the list. 由于“ e”存在于列表中,但不存在于数组中,因此需要从列表中删除“ e”。 I know the commands (.contains(), .remove(), for()), I just can't figure out the logic.
我知道命令(.contains()、. remove(),for()),我只是无法弄清楚逻辑。
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. 但这会在player [x]包含activePlayers没有的项目时从activePlayers中删除x,这很好。 It needs to be the other way around.
它需要反过来。
What you're looking for is Collection.retainAll
. 您正在寻找的是
Collection.retainAll
。
Retains only the elements in this collection that are contained in the specified collection
仅保留此集合中包含在指定集合中的元素
list.retainAll(Arrays.asList(array));
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 } {A,B,C}
if you remove B, you end up with: 如果删除B,最终得到:
{ A, C } {A,C}
When x increments, you end up with x = 3, which used to point at C. But now it points at nothing. 当x递增时,您最终得到x = 3,该值曾经指向C。但是现在它什么也没有指向。
Instead, look into using an iterator. 而是考虑使用迭代器。 See: Iterator in Java
请参阅: 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. 因此,为了回答您的问题,我将在activePlayers上创建一个迭代器。 As you iterate, simply check each item in the iterator against the list, and remove the item if is not found.
进行迭代时,只需对照列表检查迭代器中的每个项目,如果未找到则将其删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.