關於java.util.ConcurrentModificationException
阿新 • • 發佈:2019-01-30
此異常發生在使用迭代器(Iterator)時,如果迭代器內的物件發生改變,則會發生此異常。
程式碼演示
public class iteratorDemo {
public static void main(String[] args) {
Collection c = new HashSet();
c.add(new Name("ffff1","222"));
c.add(new Name("f2","adwe"));
c.add(new Name("fff3","ssha"));
Iterator i = c.iterator();
while (i.hasNext()){
Name name = (Name) i.next();
if(name.getFirstName().length() < 3){
i.remove(name);
//如果換成c.remove(name);會產生例外;
//java.util.ConcurrentModificationException
}
}
System.out.println(c);
}
Name類
public class Name {
private String firstName,lastName;
public Name(){}
public Name(String firstName, String lastName) {
super();
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String toString(){
return firstName+" "+lastName;
}
}
在while迴圈內部,執行的是Iterator物件,遍歷的過程是封閉的過程,所以當迴圈內部的物件發生變化時,就會發生異常