List remove操作注意问题

来源:互联网 发布:小猪cms最新源码下载 编辑:程序博客网 时间:2024/05/21 20:45
public static void main(String[] args) {// TODO Auto-generated method stubList<String> list = new ArrayList<String>();list.add("A");list.add("B");list.add("C");list.add("D");list.add("E");for(int i = 0;i<list.size();i++){if(!"A".equals(list.get(i))){list.remove(i);}}System.out.println("--查看结果--");for(int i = 0;i<list.size();i++){System.out.println(list.get(i));}}


上面代码是要删除List集合中内容不为A的值

输出结果应该为A

可竟然是A C E

原因:List每remove掉一个元素以后,后面的元素都会向前移动,此时如果执行i=i+1,则刚刚移过来的元素没有被读取。

解决方法:

1、每移除一个元素以后再把i移回来


for(int i = 0;i<list.size();i++){if(!"C".equals(list.get(i))){list.remove(i);i=i-1;}}

2、使用iterator.remove()方法删除

for(Iterator ite = list.iterator();ite.hasNext();){if(!"C".equals(ite.next())){ite.remove();}}

3.倒过来遍历list
for(int i = list.size()-1;i>=0;i--){if(!"C".equals(list.get(i))){list.remove(i);}}

注意:

如果for-each遍历时删除元素将报
Exception in thread "main" java.util.ConcurrentModificationException异常

for(String s:list){if(!"C".equals(s)){list.remove(s);}}



原创粉丝点击