课程: Learning Java Collections

今天就学习课程吧!

今天就开通帐号,24,700 门业界名师课程任您挑!

Modifying collections while iterating

Modifying collections while iterating - Java教程

课程: Learning Java Collections

Modifying collections while iterating

- [Instructor] When beginning to iterate through collections, most Java developers encounter the concurrent modification exception. It's almost like a rite of passage. So I'm going to show you how to avoid that. In our application, I've created a collection of rooms. Then we have some innocent looking code that iterates through the rooms using a for-each loop. Inside of the loop's body, we check to see if a room is pet friendly. Pet friendly is a new Boolean field that I've added to the room type and added accessors for. If the room is pet friendly, we're going to attempt to remove it from the collection of rooms. Now let's go ahead and see what happens when we execute this code. Yup, there it is, the concurrent modification exception. So let's talk a little bit about why that occurred. The concurrent modification exception is thrown when the underlying collection is modified while we're iterating through it. It can be…

内容