[英]How do I remove values found in one ArrayList from another ArrayList?
I have two ArrayLists 我有两个ArrayList
ArrayList<Integer> values = new ArrayList<Integer>();
values.add(9);
That's one, here's the other: 那是一个,这里是另一个:
ArrayList<Integer> values2 = new ArrayList<Integer>();
for(int j = 1; j < 10; j++){
values2.add(j);
}
How can I compare the two and remove 9 from the second ArrayList? 如何比较两者并从第二个ArrayList中删除9? I tried using a foreach statement but I kept getting
我尝试使用foreach语句,但是我不断
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 9, Size: 1
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
This had been a head-peck for some hours now and I appreciate any help you can offer 这已经花了几个小时了,我很感激您能提供的任何帮助
You use 你用
values2.removeAll(values);
From the Javadoc for the Collection
interface ( http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html ) - 从Javadoc的“
Collection
界面( http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html)-
boolean removeAll(Collection c)
boolean removeAll(Collection c)
Removes all of this collection's elements that are also contained in the specified collection (optional operation).
删除指定集合中也包含的所有此集合元素(可选操作)。 After this call returns, this collection will contain no elements in common with the specified collection.
在此调用返回之后,此集合将不包含与指定集合相同的元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.