Java Gotchas

This is ongoing post where i hope to continue list different Java gotches

1. java.util.ConcurrentModificationException – Removing children from the parents’s collection while we’re iterating over it.

As example we use groovy. In our example, we have RentalUnit object that contains colection of Reviews and Reviews contain collection of RentalUnit all in many-to-many relationship

Error:

review1.rentalUnits*.removeFromReviews(review1)

Solution:

def r = []
r += review1.rentalUnits
r.each {RentalUnit renUnit ->
     renUnit.removeFromReviews(review1)
}