我正在尝试搜索数组列表以查找一个值(可能会再次出现)并删除该值的所有实例。我还想从单独的数组列表中删除位于同一位置的值。两个 ArrayList 都是 ArrayList<String>
.
例如,我正在 ArrayList2 中查找数字 5:
ArrayList 1 ArrayList2
cat 1
pig 2
dog 5
chicken 3
wolf 5
一旦我在两个位置找到数字 5,我就想从 ArrayList1 中删除狗和狼。我的代码没有错误,但它似乎并没有真正删除我所要求的内容。
//searching for
String s="5";
//for the size of the arraylist
for(int p=0; p<ArrayList2.size(); p++){
//if the arraylist has th value of s
if(ArrayList2.get(p).contains(s)){
//get the one to remove
String removethis=ArrayList2.get(p);
String removetoo=ArrayList1.get(p);
//remove them
ArrayList2.remove(removethis);
ArrayList1.remove(removetoo);
}
}
当我打印 arrayList 时,它们看起来基本上没有变化。有人看到我做错了什么吗?
最佳答案
当您同时循环并从数组中删除项目时,您编写的算法是不正确的,因为它会跳过每次删除后的下一个项目(由于您递增 p 的方式)。考虑这个替代方案:
int s = 5;
int idx = 0;
while (idx < ArrayList2.size())
{
if(ArrayList2.get(idx) == s)
{
// Remove item
ArrayList1.remove(idx);
ArrayList2.remove(idx);
}
else
{
++idx;
}
}
关于Java ArrayList 搜索和删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12111210/