如何通过检查其值从

如何通过检查其值从

本文介绍了如何通过检查其值从 ArrayList 中删除元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ArrayList,我想从中删除一个具有特定值的元素...

I have ArrayList, from which I want to remove an element which has particular value...

例如.

ArrayList<String> a=new ArrayList<String>();
a.add("abcd");
a.add("acbd");
a.add("dbca");

我知道我们可以迭代 arraylist 和 .remove() 方法来删​​除元素,但我不知道在迭代时如何做.如何删除值为acbd"的元素,即第二个元素?

I know we can iterate over arraylist, and .remove() method to remove element but I dont know how to do it while iterating.How can I remove element which has value "acbd", that is second element?

推荐答案

在您的情况下,不需要遍历列表,因为您知道要删除哪个对象.您有多种选择.首先,您可以通过索引删除对象(因此,如果您知道该对象是第二个列表元素):

In your case, there's no need to iterate through the list, because you know which object to delete. You have several options. First you can remove the object by index (so if you know, that the object is the second list element):

 a.remove(1);       // indexes are zero-based

或者,您可以删除第一次出现的字符串:

Or, you can remove the first occurence of your string:

 a.remove("acbd");  // removes the first String object that is equal to the
                    // String represented by this literal

或者,删除具有特定值的所有字符串:

Or, remove all strings with a certain value:

 while(a.remove("acbd")) {}

这有点复杂,如果您的集合中有更复杂的对象并且想要删除具有特定属性的实例.这样您就无法通过对与您要删除的对象相同的对象使用 remove 来删除它们.

It's a bit more complicated, if you have more complex objects in your collection and want to remove instances, that have a certain property. So that you can't remove them by using remove with an object that is equal to the one you want to delete.

在这种情况下,我通常使用第二个列表来收集我想删除的所有实例,并在第二遍中删除它们:

In those case, I usually use a second list to collect all instances that I want to delete and remove them in a second pass:

 List<MyBean> deleteCandidates = new ArrayList<>();
 List<MyBean> myBeans = getThemFromSomewhere();

 // Pass 1 - collect delete candidates
 for (MyBean myBean : myBeans) {
    if (shallBeDeleted(myBean)) {
       deleteCandidates.add(myBean);
    }
 }

 // Pass 2 - delete
 for (MyBean deleteCandidate : deleteCandidates) {
    myBeans.remove(deleteCandidate);
 }

这篇关于如何通过检查其值从 ArrayList 中删除元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 17:01