File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Regarding Collections Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Regarding Collections" Watch "Regarding Collections" New topic

Regarding Collections

Prasad Maddipatla

Joined: Apr 20, 2007
Posts: 24
Hi ,

import java.util.*;

public class PQ
public static void main(String[] args)
PriorityQueue<String> pq = new PriorityQueue<String>();


for(String s q)


I am getting RuntimeException ... can any one help me out.
Prasad Maddipatla

Joined: Apr 20, 2007
Posts: 24
hi friends its

for(String s : pq)
Gaurav Joshi

Joined: Mar 08, 2008
Posts: 18
Hi Prasad Maddipatla

Line 1 uses Enhanced for loop, alternative for Iterator, implicitly iterators are used, hence the above for loop line can be substituted for

Now the first iteration of for loop will execute smoothly and apple will be added, but as implicit iterator excutes and performs s = , Concurrent Modification Run Time Exception is Thrown
Hence if Iterator used, addition an deletion should always be done through Iterator
Khushbu Ghodasara
Ranch Hand

Joined: May 09, 2007
Posts: 35
Originally posted by Prasad Maddipatla:

for(String s : pq)

this is the line which is causing the runtime exception.

here you are getting ConcurrentModificationException
That is because you are concurrently iterating a Collection and modifying the same collection. here is the excerpt taken from J2SE 5.0 API,

public class ConcurrentModificationException
extends RuntimeException

This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.

For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances.

I agree. Here's the link:
subject: Regarding Collections
It's not a secret anymore!