遍历List,删除其中元素的正确做法
2015-11-27 19:35
405 查看
在for循环遍历List,不能直接remove到其中的元素。正确的做法是巧用Iterator迭代器。如下:
将年龄大于30岁的记录删除,最后结果是3.
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.
相关文章推荐
- C++ 干掉进程的一个方法
- 百度地图开发之 坐标转换
- php学习笔记六:PHP-基本语法
- window下获取mac地址
- Android使用okhttp下载图片
- 1593: [Usaco2008 Feb]Hotel 旅馆
- Linux兄弟连视频学习笔记
- onConfigurationChanged未被调用的原因
- 函数的应用
- Broadcast
- CF 601C(Kleofáš and the n-thlon-期望dp)
- 线程create时参数的传递问题(转载)
- Android自定义View动画(进度条)
- 主席树初步
- 人民币金额拆分——很笨的一种方法(没完善)
- python内置函数
- 《FPGA全程进阶---实战演练》第二章之硬件平台的搭建
- POJ 2991 Crane
- 黑马程序员--杨辉三角形问题
- IntelliJ IDEA 常用快捷键列表