Java ArrayList搜索和删除

Ste*_*lis 3 java arraylist

我试图搜索数组列表以查找值(可能会重新发生)并删除该值的所有实例.我还想从单独的数组列表中删除位于同一位置的值.两个ArrayLists都是ArrayList<String>.

例如,我在ArrayList2中寻找数字5:

ArrayList 1       ArrayList2
cat               1
pig               2
dog               5
chicken           3
wolf              5
Run Code Online (Sandbox Code Playgroud)

一旦我在两个位置找到数字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);
  }
}
Run Code Online (Sandbox Code Playgroud)

当我打印数组列表时,它们看起来基本没有变化.有谁看到我做错了什么?

小智 9

当您同时循环并从数组中删除项目时,您编写的算法不正确,因为它会在每次删除后跳过下一个项目(由于您增加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;
  }
}
Run Code Online (Sandbox Code Playgroud)