本帖最后由 陈永波 于 2012-6-30 22:16 编辑
题目:定义方法, 接收一个已装入Person对象的List, 删除List中age为20的Person
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Exercise2 {
public static void main(String[] args) {
List list = new ArrayList();
list.add(new Person("小1",21));
list.add(new Person("小2",22));
list.add(new Person("小3",20));
list.add(new Person("小4",20));
for(int i = 0; i < list.size(); i++){
Person p = (Person)list.get(i);
if(p.getAge()==20)
list.remove(p);
i--;
}
System.out.println(list);
}
/*
for(int i = 0; i < list.size(); i++){
Person p = (Person)list.get(i);
if(p.getAge()==20)
list.remove(i--);
}
System.out.println(list);
}
*/
}
class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
问题:红色部分是正确代码,蓝色部分是错误代码.为什么删除P对象 remove(p),i--;不可以呢,而是需要remove(i--);?最好详细回答 蓝色的代码貌似会出现死循环 |
|