您的位置:首页 > 其它

遍历List,删除其中元素的正确做法

2015-11-27 19:35 405 查看
在for循环遍历List,不能直接remove到其中的元素。正确的做法是巧用Iterator迭代器。如下:

public class People{
public int age;
public String gender;
public People(int age,String gender){
this.age = age;
this.gender = gender;
}

public static void main(String[] args) {
List<People> lists = new ArrayList<People>();
People p1 = new People(13, "Woman");
lists.add(p1);
People p2 = new People(24, "Man");
lists.add(p2);
People p3 = new People(25,"Woman");
lists.add(p3);
People p4 = new People(34,"Man");
lists.add(p4);

for(Iterator<People> it = lists.iterator();it.hasNext();){
People people = it.next();
if(people.age>30){
it.remove();//注意这里是it不是lists
}
}
System.out.println(lists.size());
}
}


将年龄大于30岁的记录删除,最后结果是3.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: