Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes PriorityQueue 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 "PriorityQueue" Watch "PriorityQueue" New topic
Author

PriorityQueue

sumi selva
Greenhorn

Joined: Jul 10, 2007
Posts: 19
I executed the following code.
import java.util.*;

class DemoPQ {
public static void main(String[] args) {
PriorityQueue<String> pq = new PriorityQueue<String>();
pq.add("Ravi");
pq.add("Kumar");
pq.add("Sumit");
pq.add("Vineet");
pq.add("Amit");

for(String s q) {
System.out.print(pq.peek() + ", " + pq.poll());

}
}

}

Got the output as Amit followed by ConcurrentModificationException.
May I know why does this exception come?

Thanks,
Sumi
Srinivasan thoyyeti
Ranch Hand

Joined: Feb 15, 2007
Posts: 557
I think polling(removing element) causing the Iteration get effected. try to poll outside the loop.


Thanks & Regards, T.Srinivasan
SCWCD 1.4(89%), SCJP 5.0(75%)
christian combarel
Ranch Hand

Joined: Aug 04, 2007
Posts: 47
Hi,
For each iteration the current thread (main) read an element from the Queue and then alter it with the poll method.
So at the second iteration, the content of collection (pq) has changed and it's the cause of the throw of ConcurrentModificationException. Read the Javadoc of it.

If you write something like :

it works fine.



-------------
Chris
 
GeeCON Prague 2014
 
subject: PriorityQueue