Java ArrayList 搜索和删除 [英] Java ArrayList search and remove

查看:29
本文介绍了Java ArrayList 搜索和删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试搜索数组列表以查找值(可能会再次出现)并删除该值的所有实例.我还想从单独的数组列表中删除位于同一位置的值.两个 ArrayList 都是 ArrayList.

I am attempting to search through an array list to find a value (which may reoccur) and remove all instances of that value. I also would like to remove from a separate array list, values that are at the same location. Both ArrayLists are ArrayList<String>.

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

For example I am looking for the number 5 in ArrayList2:

ArrayList 1       ArrayList2
cat               1
pig               2
dog               5
chicken           3
wolf              5

在两个位置找到数字 5 后,我想从 ArrayList1 中删除 dog 和 wolf.我的代码没有错误,但它似乎并没有真正消除我的要求.

Once I find the number 5, in both locations, I would like to remove dog and wolf from ArrayList1. My code has no errors but it doesn't seem to be actually removing what I am asking it.

//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 时,它们看起来基本没有变化.有人看到我做错了什么吗?

When I print the arrayLists they look largely unchanged. Anyone see what I am doing wrong?

推荐答案

当你同时循环并从数组中移除项目时,你编写的算法是不正确的,因为它会在每次移除之后跳过下一个项目(由于你增加 p).考虑这个替代方案:

When you are both looping and removing items from an array, the algorithm you wrote is incorrect because it skips the next item following each removal (due to the way in which you increment p). Consider this alternative:

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 搜索和删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆