aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes changing collections in for each Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "changing collections in for each" Watch "changing collections in for each" New topic
Author

changing collections in for each

Stephen O'Kane
Greenhorn

Joined: Aug 17, 2005
Posts: 26
Given



What is the result

a.Prints hello 3 hi 2 bye 1
b.Prints hello 2 hi 1 bye 0
c.Prints bye 3 hello 2 hi 1
d.Prints bye 2 hello 1 hi 0
e.Prints bye 2 followed by an Exception.
f.None of the above.






Answer

e. bye 2 followed by ConcurrentModificationException. When the loop is iterating through the queue, you are not allowed to poll it since it changes the contents of the data structure. The same goes for offer(). Both these methods will appear on the exam.


The only question I have about this answer is, does it apply to all collections, or just those that extend Collection or just those that extend Queue, or just PriorityQueue.

Thanks in advance
Sok
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

The only question I have about this answer is, does it apply to all collections, or just those that extend Collection or just those that extend Queue, or just PriorityQueue.


This is an issue related to the behavior of the iterator (in relation to the collection). And it is implementation specific -- meaning that you'll have to keep a JavaDoc handy.

Most pre-java 5 collection's iterators, are designed to fail if the collection is changed, outside of the iterator. You can make changes, using the iterator, but changing it any other way will fail the iterator.

With Java 5, some iterators work on a "view" of the collection. If the collection is changed outside of the iterator, the iterator will actually still work on the unchanged copy of the collection.

Henry
[ August 20, 2006: Message edited by: Henry Wong ]

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: changing collections in for each