问题描述
我有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
然后,您可以删除您的字符串发生:
Then, 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中删除元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!