Java ArrayList 搜索和删除

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12111210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 07:37:25  来源:igfitidea点击:

Java ArrayList search and remove

javaarraylist

提问by Stephopolis

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>.

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

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

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

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

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.

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

//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);
  }
}

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

当我打印 arrayLists 时,它们看起来基本没有变化。有人看到我做错了什么吗?

回答by a_a_t

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:

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

回答by bpgergo

If you want to iterate over a collection and remove elements of the same collection, then you'll have to use an Iterator, e.g.:

如果要遍历集合并删除同一集合的元素,则必须使用Iterator,例如:

List<String> names = ....
List<Integer> numbers = ....
int index = 0;
Iterator<String> i = names.iterator();
while (i.hasNext()) {
   String s = i.next(); // must be called before you can call i.remove()
   if (s.equals("dog"){
       i.remove();
       numbers.remove(index);
   }
   index++;
}

EDIT

编辑

In your case, you'll have to manually increment a variable to be able to remove items from the other List.

在您的情况下,您必须手动增加一个变量才能从另一个列表中删除项目。

回答by beny23

You could use two iterators:

您可以使用两个迭代器:

Iterator<String> i1 = arrayList1.iterator();
Iterator<Integer> i2 = arrayList2.iterator();
while (i1.hasNext() && i2.hasNext()) {
  i1.next();
  if (i2.next() == s) {
    i1.remove();
    i2.remove();
  }
}

Though as has been pointed out yet, it would probably be easier to use a map.

尽管正如已经指出的那样,使用地图可能会更容易。

回答by aioobe

Here's a straight forward solution:

这是一个直接的解决方案:

List<Integer> origNums = new ArrayList<Integer>(nums);
Iterator<String> animalIter = animals.iterator();
Iterator<Integer> numIter = nums.iterator();

while (animalIter.hasNext()) {
    animalIter.next();

    // Represents a duplicate?
    if (Collections.frequency(origNums, numIter.next()) > 1) {

        // Remove current element from both lists.
        animalIter.remove();
        numIter.remove();
    }
}

System.out.println(animals); // [cat, pig, chicken]
System.out.println(nums);    // [1, 2, 3]

回答by nbz

I agree with Makoto, using Map maybe more beneficial. If you will be searching only using the values of ArrayList2, then you have multiple values for one key. For example, 5 refers to dog and wolf. For this you can add a list of values to the key - 5.

我同意 Makoto,使用 Map 可能更有益。如果您将仅使用 ArrayList2 的值进行搜索,那么一个键就有多个值。例如,5 指的是狗和狼。为此,您可以将值列表添加到键 - 5。

HashMap aMap = HashMap();

ArrayList key5 = new ArrayList();

key5.add("dog");
key5.add("wolf");

aMap.put(5, key5);

So when you need to remove all values for 5, you do

因此,当您需要删除 5 的所有值时,您可以

aMap.remove(5);

And it will remove the list containing dog and wolf.

它将删除包含狗和狼的列表。

回答by fgp

You might want to check the indexOf()method of ArrayList, but you have to be careful when removing from a list while iterating on it's elements.

您可能想要检查ArrayList的indexOf()方法,但在迭代列表元素时从列表中删除时必须小心。

回答by Sharg

I think the contains method compares the two objects. However, the object "s" is different from the object in the ArrayList. You should use typed arrays (i.e. ArrayList) and make sure to compare values of each objects, not the objects themselves ...

我认为 contains 方法比较了两个对象。但是,对象“s”与ArrayList 中的对象不同。您应该使用类型化数组(即 ArrayList)并确保比较每个对象的值,而不是对象本身......

回答by Bhesh Gurung

You should declare your list as follows -

您应该如下声明您的清单 -

List<String> list1 = new ArrayList<String>();
//...
List<Integer> list2 = new ArrayList<Integer>();
//...

And instead of containsmethod use equalsmethod.

而不是contains方法使用equals方法。

Also to remove while iterating the lists use Iteratorwhich you can get as follows -

还可以在迭代列表时删除Iterator,您可以获得如下 -

Iterator<String> it1 = list1.iterator();
Iterator<Integer> it2 = list2.iterator();

//...