编辑:
我的第一个答案(线下)实际上是WRONG,就像迄今为止发布的所有其他人一样。我做了一个小测试(如下)......我们都在迭代器中导致了ConcurrentModificationException,它是 foreach 循环的基础。现在有一个问题给你!叹。
package forums;
import java.util.List;
import java.util.ArrayList;
class Person
{
private final String name;
private final int age;
Person(String name, int age) {
this.name=name;
this.age=age;
}
public String getName() { return name; }
public int getAge() { return age; }
public String toString() { return name + " " + age; }
}
public class PeopleTest
{
public List<Person> people;
public void remove(String name)
{
for ( int i=0; i<people.size(); i++ ) {
Person person = people.get(i);
if (person.getName().equals(name)) {
people.remove(person);
i--;
}
}
}
public void badRemove(String name)
{
for ( Person person : people ) {
if (person.getName().equals(name)) {
people.remove(person);
}
}
}
public void printAll(String message) {
System.out.println(message);
for ( Person person : people ) {
System.out.println(" " + person);
}
}
public void run()
{
// setup
people = new ArrayList<Person>(5);
Person dave, kelly, jack, jill, xavier;
people.add(dave=new Person("Dave", 36));
people.add(kelly=new Person("Kelly", 25));
people.add(jack=new Person("Jack", 42));
people.add(jill=new Person("Jill", 19));
xavier = new Person("Xavier", 136);
badRemove("Dave");
// before image
assert people.size() == 4;
printAll("the before list");
// operation 1
assert !people.contains(xavier);
remove("Xavier"); // a no-op.
assert people.size() == 4;
assert !people.contains(xavier);
// operation 2
assert people.contains(jill);
remove("Jill"); // she smells!
// after image
printAll("the after list");
assert people.size() == 3;
assert people.contains(dave);
assert people.contains(kelly);
assert people.contains(jack);
assert !people.contains(jill);
}
public static void main(String[] args) {
try {
new PeopleTest().run();
} catch (Exception e) {
e.printStackTrace();
}
}
}
输出
C:\Java\home\src\forums>"C:\Program Files\Java\jdk1.6.0_16\bin\java.exe" -Xms4m -Xmx256m -enableassertions -cp c:\java\home\src;C:\Java\home\classes; forums.PeopleTest
java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
at forums.PeopleTest.badRemove(PeopleTest.java:36)
at forums.PeopleTest.run(PeopleTest.java:62)
at forums.PeopleTest.main(PeopleTest.java:89)
老兄,
这个答案是错误的,请忽略它!!!
我建议您改用http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html#remove%28java.lang.Object%29。
就像是:
public ArrayList<Person> people;
public void remove(String name) {
for ( Person person : people ) {
if (person.getName().equals(name)) {
people.remove(person);
}
}
}
...假设 Person 有一个getName
方法,它返回一个字符串。
干杯。基思。