Java中ArrayList的remove方法

以后删除元素不敢用ArrayList中的remove了,不知道能出现神马样的后果,删除不干净哦。在for循环中连续remove ArrayList中的元素总是会删除不干净的。

import java.util.ArrayList;

public class ArrayListTest {
	public static void main(String[] args) {
		ArrayList arrayList = new ArrayList(100);
		//初始化元素0-9
		for (int i = 0; i < 10; i++) {
			arrayList.add(String.valueOf(i));
		}
		//删除整除2的元素并很笨的打印一些信息
		for (int i = 0; i < arrayList.size(); i++) {
			System.out.println("before if:\t" + i);
			if (Integer.valueOf(arrayList.get(i)).intValue() < 2
					|| Integer.valueOf(arrayList.get(i)).intValue() > 5) {
				System.out.println("befor remove\t" + i);
				System.out.println("removing:\t" + arrayList.remove(i));
				System.out.println("after remove:\t" + i);
			}
			System.out.println("after if:\t" + i);
		}

		System.out.println("*************************************");

		for (int i = 0; i < arrayList.size(); i++) {
			System.out.println(arrayList.get(i));
		}
	}
}

 

你看看结果哦,感觉运行步骤是蹦蹦跳跳滴。

before if:	0
befor remove	0
removing:	0
after remove:	0
after if:	0
before if:	1
after if:	1
before if:	2
after if:	2
before if:	3
after if:	3
before if:	4
after if:	4
before if:	5
befor remove	5
removing:	6
after remove:	5
after if:	5
before if:	6
befor remove	6
removing:	8
after remove:	6
after if:	6
*************************************
1
2
3
4
5
7
9

 谁能给我解释下这是为什么呢? 求解!!

你可能感兴趣的:(Java)