---
title: "遍历同时删除内容时的哨兵问题"
author: "xusulong"
date: "2010-03-04T09:49:13Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2010-03-04T09:49:13Z"
id: 607469
url: "https://xusulong.iteye.com/blog/607469"
---

这是我在做rdf的sentence时候遇到的问题，本来以为是个很复杂的问题，最后才发现是一个不起眼的地方酿成的大错。

此问题可以简单示例成如下问题：

找到ArrayList a = {"a", "\*", "\*", "b", "\*", "\*", "c"}中为"\*"的那些元素，并且将这些元素删除

开始的时候不假思索就写下了下面的代码

# 错误的写法

```
public static void guardProblem(ArrayList<String> a) {
		for(int i = 0; i < a.size(); i ++) {
			if(a.get(i).equals("*")) {
				a.remove(i);
			} 
		}
	}
	public static void main(String []args) {
		ArrayList<String> a = new ArrayList<String>();
		Collections.addAll(a, "a", "*", "*", "b", "*", "*", "c");
		guardProblem(a);
		System.out.println(a);
	}
}
```

 但是发现删除之后数组为\[a, \*, b, \*, c]，调试发现其中有两个\*被跳过了。

# 原因：

删除的时候，a的size变了，因此这时候的i假如递增就不能够遍历整个数组了，应该在没有删除的时候递增，删除的时候保持i不变

# 正确的写法

```
public class Test {
	public static void guardProblem(ArrayList<String> a) {
		for(int i = 0; i < a.size();) {
			if(a.get(i).equals("*")) {
				a.remove(i);
			} else {
				i ++;
			}
		}
	}
	public static void main(String []args) {
		ArrayList<String> a = new ArrayList<String>();
		Collections.addAll(a, "a", "*", "*", "b", "*", "*", "c");
		guardProblem(a);
		System.out.println(a);
	}
}
```

 这时候的结果就正确了，删除之后a为\[a, b, c]