Java的ArrayList中搜索并删除 [英] Java ArrayList search and remove

查看:489
本文介绍了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去除狗与狼。我的code没有错误,但它似乎并没有被真正删除什么,我问它。

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天全站免登陆