一、ArrayList循环删除错误
今天再写删除ArrayList里面的某个元素时,以为简单循环找出元素在进行删除就可以了,但是却出现了错误。
错误写法一:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("aa"); list.add("bb"); list.add("bb"); list.add("cc"); list.add("cc"); list.add("dd"); System.out.println("删除前: " + list); for (int i = 0; i < list.size(); i++) { if ("cc".equals(list.get(i))){ list.remove(i); } } System.out.println("删除后: " + list); }
结果为:
错误写法二
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("aa"); list.add("bb"); list.add("bb"); list.add("cc"); list.add("cc"); list.add("dd"); System.out.println("删除前: " + list); for (String s : list) { if ("bb".equals(s)) { list.remove(s); } } System.out.println("删除后: " + list); }
结果为:
二、错误分析
首先看下ArrayList中的remove方法
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17public 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(index)方法:
复制代码
1
2
3
4
5
6
7
8
9private void fastRemove(int index) { modCount++; int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear to let GC do its work }
对于错误一:
由于执行System.arraycopy方法,导致删除元素时涉及到数组元素的移动。在遍历第二个元素字符串cc时因为符合删除条件,所以将该元素从数组中删除,之后的整个数组就和集体往前移动,此次循环结束后的累加器又 +1,所有相邻的一个就会被忽略掉。
对于错误二:
foreach写法是对实际的Iterable、hasNext、next方法的简写,问题同样在fastRemove方法中,由于第一行中把modCount变量的值加一,但在ArrayList返回的迭代器。
三、解决办法
1、删除后,将指针往前移一位。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("aa"); list.add("bb"); list.add("bb"); list.add("cc"); list.add("cc"); list.add("dd"); System.out.println("删除前: " + list); for (int i = 0; i < list.size(); i++) { if ("cc".equals(list.get(i))){ list.remove(i--); } } System.out.println("删除后: " + list); }
2、迭代器删除
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("aa"); list.add("bb"); list.add("bb"); list.add("cc"); list.add("cc"); list.add("dd"); System.out.println("删除前: " + list); Iterator<String> iterator = list.iterator(); while (iterator.hasNext()){ if("cc".equals(iterator.next())){ //使用迭代器删除 iterator.remove(); //在迭代器中用list会报错 //list.remove("cc"); } } System.out.println("删除后: " + list); }
结果均为:
最后
以上就是慈祥山水最近收集整理的关于ArrayList循环删除元素的常见问题及解决方法的全部内容,更多相关ArrayList循环删除元素内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复