問題描述:
Java新手容易犯一個錯誤,就是周遊集合的同時删除集合的元素。那麼程式會發生什麼呢?下面舉個小例子。
import java.util.HashSet;
import java.util.Iterator;
public class IterAndRemove {
public static void main(String[] args) {
HashSet<String> set = new HashSet<String>();
set.add("zq");
set.add("allen");
set.add("alex");
delete(set);
//delete1(set);
for(String s : set){
System.out.println(s);
}
}
public static void delete(HashSet<String> hashSet) {
for(String s : hashSet){
if(s.equals("alex")){
hashSet.remove(s);
}
}
}
public static void delete1(HashSet<String> hashSet) {
Iterator<String> iterator = hashSet.iterator();
while(iterator.hasNext()){
String s = iterator.next();
if(s.equals("alex")){
iterator.remove();
}
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
程式執行delete()方法,發生錯誤。

執行方法delete1()方法,則程式正确的傳回:
allen
zq
- 1
- 2
- 1
- 2
是以,可以采用Iterator中的remove()方法來實作集合的一邊删除一邊周遊。