Jump to content
Search In
  • More options...
Find results that contain...
Find results in...

(Java) Does only foreach give exception when editing collection elements?

Kiyullo
 Share

I'm using Java 17 (if it matters).

 

I'm confused about the nature of adding/removing elements from a collection in loops (for, foreach, while, ETC). I thought that foreach loops couldn't be used to add/remove elements, but after testing, I can remove only one element, and anymore will give ConcurrentModificationException exception.

Also I thought that adding/removing elements in any of the other loops would give ConcurrentModificationException exception unless using an Iterator. After testing it, I can remove multiple elements without an Iterator.

 

The main reason I'm confused is because I thought I learned and tested this before and confirmed different outcomes, but perhaps I'm remembering wrong, or maybe things worked differently on an older Java version I was using?

 

So what are the facts, really?

 

Can foreach be used to add/remove only one element from a collection?

 

Do Iterators need to be used in loops to add/remove elements from collections?

Java Trainee (Novice)

Thanks in advance~

Link to comment
Share on other sites

Link to post
Share on other sites

IIRC from my java classes, for each loops are not meant to edit something. They are just used for getting values from a collection or printing or sth like that. But that could just be a wrong memory from me

Link to comment
Share on other sites

Link to post
Share on other sites

I'm a beginner in Java (I work with other languages usually) but here's what I think.

By for loop, do you mean iterating through 0 to the collection's size, then using methods like .get(i) for the items? If so, then that's not proper iteration, because those methods iterate through the collection each time, instead of continuing from the last item (a new iteration each time). That's why you don't see ConcurrentModificationException being thrown.

A for each loop is using an iterator under the hood anyway, so use an iterator if you need to remove as you go.

Intel Core i3-10100 - Gigabyte Z490M - HyperX DDR4 16GB  - 500W - 1x 1080p - macOS 12 Monterey, Windows 11

Intel Core i5-4210U - Acer Aspire E5-573G - 8GB - 768p - macOS 11 Big Sur, Windows 11
iPhone 12 - iOS 16

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share


×