您的位置:首页 > 编程语言 > Java开发

java--容器---ArrayList的删除

2015-11-11 18:40 615 查看
ArrayList是经常使用的容器,在删除元素的时候经常出错

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);

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: