java.util.List的remove()方法使用技巧(转)
来源:互联网 发布:php写android服务器端 编辑:程序博客网 时间:2024/05/22 00:08
一.list.remove(i)
de >public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(3); list.add(3); list.add(4); for (int i=0; i<list.size(); i++) { if (list.get(i) == 3) { list.remove(i);//这样写不对,需要写成list.remove(i--) } } System.out.println(list);} de>
如果要遍历list进行过滤,比如过滤掉值为3的对象。本以为这代码再简单不过,可还是掉坑里了,上面的代码这样写的话,元素3是过滤不完的。只要list中有相邻2个相同的就过滤不完List调用remove(index)方法后,会移除index位置上的元素,index之后的元素就全部依次左移,即索引依次-1要保证能操作所有的数据,需要把index-1,否则原来索引为index+1的元素就无法遍历到(因为原来索引为index+1的数据,在执行移除操作后,索引变成index了,如果没有index-1的操作,就不会遍历到该元素,而是遍历该元素的下一个元素)。
同样,Map通过keySet()或entrySet()遍历时,不能删除里面的元素,否则会报java.util.ConcurrentModificationException
为了避免出现以上情况,需要对List或Map进行遍历且要进行删除操作时一定要使用迭代器Iterator,通过iterator.remove()来删除。
二.建议使用iterator.remove方法
de >if (null != list && list.size() > 0) { Iterator it = list.iterator(); while(it.hasNext()){ Student stu = (Student)it.next(); if (stu.getStudentId() == studentId) { it.remove(); //移除该对象 } }} de>
阅读全文
0 0
- java.util.List的remove()方法使用技巧(转)
- java.util.List的remove()方法使用技巧
- java.util.HashMap.remove()方法的使用
- 关于 list.remove(obj);方法在迭代器中报java.util.ConcurrentModificationException
- list执行remove和add方法时,报java.util.ConcurrentModificationException的原因
- Arrays.asList() 返回的list不能add,remove以及慎用java.util.Collections.copy()方法
- java.util.List接口的方法subList()的使用注意事项
- java.util.List接口的方法subList()的使用注意事项
- java.util.List接口的方法subList()的使用注意事项
- java.util.List里的subList方法使用
- JAVA.util.Collections List的常用方法,sort()
- List对象remove方法的使用
- List对象remove方法的使用
- 关于java List的remove方法
- java 中执行list 的remove 方法
- Java中List的remove方法
- Java List的remove()方法陷阱
- list的remove方法
- JSTL标签库
- 震惊!慢SQL居然能优化到这种速度_我不服!
- mysql中的limit用法(转)
- 开发人员学Linux(9):CentOS7编译安装Git-2.13.1及使用
- Jps介绍以及解决jps无法查看某个已经启动的java进程问题
- java.util.List的remove()方法使用技巧(转)
- LDA主题模型的理解与实践
- 远程连接数据库
- Netty的protobuf的图书订购服务端开发
- 安卓流式布局——标签墙
- RabbitMQ PHP扩展安装
- 我学xingo golang服务器之-Unity3d c# 协议api分解
- C语言复习 第二波
- POJ 1383 Labyrinth 【树的直径】【真正的图】