参考资料
java.util.ConcurrentModificationException详解
Java ConcurrentModificationException异常原因和解决方法
报错
Exception in thread "main" java.util.ConcurrentModificationException
at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:937)
at java.base/java.util.ArrayList$Itr.next(ArrayList.java:891)
at Book.RemoveAuthor(Part1_1.java:38)
at Part1_1.main(Part1_1.java:11)
代码
public class Part1_1{
public static void main(String[] args) {
Author author1 = new Author("Richard Hartley", "123456@gamil.com", 'M');
Book aBook = new Book("Multiple View Geometry",author1,100,10);
Author author2 = new Author("Peter", "456789@gamil.com", 'F');
aBook.AddAuthor(author2);
System.out.print(aBook.toString());
System.out.print("\n");
aBook.RemoveAuthor("Peter");
System.out.print(aBook.toString());
}
}
public void RemoveAuthor(String name){
for(Author author:authors){
if(author.getName() == name){
authors.remove(author);
}
}
}
由于自身水平有限,对于参考资料的讲解,理解的并不透彻,资料中提供的解决方案看起来并不那么友好。笔者基于自己的理解,尝试换一种迭代方式试试。
代码
public void RemoveAuthor(String name){
for(int i = 0; i< authors.size(); i++){
if(authors.get(i).getName() == name){
authors.remove(authors.get(i));
}
}
}
结果
Book[ name = Multiple View Geometry,[Author[ name = Richard Hartley, email = 123456@gamil.com, gender = M], Author[ name = Peter, email = 456789@gamil.com, gender = F]], price = 100.0, qty = 10]
Book[ name = Multiple View Geometry,[Author[ name = Richard Hartley, email = 123456@gamil.com, gender = M]], price = 100.0, qty = 10]
刘月林
写于浙江宁波
20181018
网友评论