File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

PriorityQueue

 
sumi selva
Greenhorn
Posts: 19
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 557
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think polling(removing element) causing the Iteration get effected. try to poll outside the loop.
 
christian combarel
Ranch Hand
Posts: 47
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic