Java ArrayList删除元素时失败

今天想要通过遍历ArrayList,删除指定值的元素的时候遇到了个问题。

示例如下:

package cn.sehzh;

import java.util.ArrayList;
import java.util.List;

class Main{
	public static void main(String[] args) {
		List list;
		list = new ArrayList();
		
		list.add("asd");
		list.add("asd");
		list.add("qwe");

		System.out.println("before delete......");
		for (String string : list) {
			System.out.println(string);
		}
		for (int i = 0; i < list.size(); i++) {
			if("asd".equals(list.get(i))){
				list.remove(i);
			}
		}
		System.out.println("after delete......");
		for (String string : list) {
			System.out.println(string);
		}
	}
}
想要的效果为:

before delete......
asd
asd
qwe
after delete......
qwe

实际结果为:

before delete......
asd
asd
qwe
after delete......
asd
qwe

原因:在遇到匹配的元素后,list.remove(i),list的size就会减1,这样就会跳过下一个元素。

解决办法:倒序遍历

package cn.sehzh;

import java.util.ArrayList;
import java.util.List;

class Main {
	public static void main(String[] args) {
		List list;
		list = new ArrayList();

		list.add("asd");
		list.add("asd");
		list.add("qwe");

		System.out.println("before delete......");
		for (String string : list) {
			System.out.println(string);
		}
		for (int i = list.size() - 1; i >= 0; i--) {
			if ("asd".equals(list.get(i))) {
				list.remove(i);
			}
		}
		System.out.println("after delete......");
		for (String string : list) {
			System.out.println(string);
		}
	}
}
输出结果:

before delete......
asd
asd
qwe
after delete......
qwe


你可能感兴趣的:(Java)