I got an issue with deleting an object from ArrayList when working on the assignment
If I use the “normal” for loop, it works as following
public void returnBook(String isbn){
for (int i = 0; i < booksBorrowed.size(); i++){
if (booksBorrowed.get(i).getISBN() == isbn){
booksBorrowed.get(i).returnBook();
booksBorrowed.remove(i);
}
}
}
However, when I’m trying to simplify the code with enhanced for-loop, that doesn’t work and showing java.util.ConcurrentModificationException error:
public void returnBook(String isbn){
for (Book book: booksBorrowed){
if (book.getISBN() == isbn){
book.returnBook();
booksBorrowed.remove(book);
}
}
}
Hope you guys could lighten me up..
Your alternatives to avoid a ConcurrentModificationException are:
Collect all the records that you want to delete on enhanced for loop, and after you finish iterating, you remove all found records.
Or you may use a
ListIteratorwhich has support for a remove method during the iteration itself.Or you may use a third-party library like LambdaJ and it makes all the work for you behind the scenes>