java--容器---ArrayList的删除
2015-11-11 18:40
615 查看
ArrayList是经常使用的容器,在删除元素的时候经常出错
错误例子一:
运行结果:
元素a1bc
元素a2bc
元素a3bc
元素abc
元素abc
发现里面有“abc”是没有删除的。
来分析一下原因和解决办法:查找源码Object的remove()发现:
查看fastRemove()的源码
里面有个system.arraycopy方法,导致删除元素时涉及到数组元素的移动。针对错误写法一,在遍历第一个字符串acb时因为符合删除条件,所以将该元素从数组中删除,并且将后一个元素移动(也就是第二个字符串abc)至当前位置,导致下一次循环遍历时后一个字符串abc并没有遍历到,所以无法删除。
针对第一种方法的话,可以这样子解决:
也可以使用倒序删除方法:
import java.util.ArrayList; public class Test2 { public static void main(String[] args) { String str = "abc"; ArrayList<String> aList = new ArrayList<String>(); aList.add("abc"); aList.add("abc"); aList.add("abc"); aList.add("a1bc"); aList.add("a2bc"); aList.add("abc"); aList.add("a3bc"); aList.add("abc"); aList.add("abc"); for (String a : aList) { System.out.println("元素:::" + a); } remove1(aList); System.out.println("删除之后。。。。。"); for (String a : aList) { System.out.println("元素" + a); }
错误例子一:
public static void remove1(ArrayList<String> list) { for (int i = 0; i < list.size(); i++) { String s = list.get(i); if (s.equals("abc")) { list.remove(s); } } }
运行结果:
元素a1bc
元素a2bc
元素a3bc
元素abc
元素abc
发现里面有“abc”是没有删除的。
来分析一下原因和解决办法:查找源码Object的remove()发现:
public boolean remove(Object o) { if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); return true; } } else { for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); return true; } } return false; }
查看fastRemove()的源码
private void fastRemove(int index) { modCount++; int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index,numMoved); elementData[--size] = null; // Let gc do its work }
里面有个system.arraycopy方法,导致删除元素时涉及到数组元素的移动。针对错误写法一,在遍历第一个字符串acb时因为符合删除条件,所以将该元素从数组中删除,并且将后一个元素移动(也就是第二个字符串abc)至当前位置,导致下一次循环遍历时后一个字符串abc并没有遍历到,所以无法删除。
针对第一种方法的话,可以这样子解决:
public static void remove1(ArrayList<String> list) { for (int i = 0; i < list.size(); i++) { String s = list.get(i); if (s.equals("abc")) { list.remove(s); i--;//把元素下标--; } } }
也可以使用倒序删除方法:
public static void remove(ArrayList<String> list) { for (int i = list.size() - 1; i >= 0; i--) { String s = list.get(i); if (s.equals("abc")) { list.remove(s); } } }
相关文章推荐
- Spring集成Quartz定时任务框架介绍和Cron表达式详解
- Eclipse快捷键 10个最有用的快捷键
- java 中 如何让一个方法内最多只能指定数量线程访问
- 在java代码中设置字体大小,可以指定单位为sp
- Java动态代理一——动态类Proxy的使用
- Java.util.regex中matcher 和pattern的用法
- eclipse代码自动提示,eclipse设置代码自动提示
- POJ 2015 JAVA
- R.java无法生成
- java动态绑定
- java.lang.ClassNotFoundException: How to resolve
- java.sql.SQLRecoverableException: IO Error: Got minus one from a read call
- java中的枚举类学习
- WebSphereMq使用JMS发送消息和接收消息
- Spring MVC测试框架详解——服务端测试
- java自带线程池和队列详细讲解
- JAVA字符串格式化-String.format()的使用
- Java 中继承了父类的一些问题、String.CopyTo方法的具体用法
- spring无法扫描jar包的问题
- jdk高版本切换低版本之后,版本号不变,解决办法