aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes PriorityQueue issue 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 "PriorityQueue issue" Watch "PriorityQueue issue" New topic
Author

PriorityQueue issue

Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707

It prints 1 4 14

My question is, why doesn't the loop goes for second iteration, even though there is still one item remaining. As I know it should thorw ConcurrentModificationException at runtime, if it would have iterated second time.

Thanks in advance,

cmbhatt
[ May 03, 2007: Message edited by: Chandra Bhatt ]

cmbhatt
Remko Strating
Ranch Hand

Joined: Dec 28, 2006
Posts: 893
I think you have a typo in your code roll() should be poll()

Now your question the last value is not returned because you are changing the Collection on which you're iterating. The collection contains 4 items. So at the first iteration you're removing 3 items. So the collection contains 1 item.

In the next loop the code searchs for a second item in the collection which isn't there because you have removed that. There is only one item which is at position 0.

For changing a collection you should use an iterator as shown in the code below



I hope this helps


Remko (My website)
SCJP 1.5, SCWCD 1.4, SCDJWS 1.4, SCBCD 1.5, ITIL(Manager), Prince2(Practitioner), Reading/ gaining experience for SCEA,
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
Sorry for the typo, it is poll() not roll.

Thanks Remko, but why doesn't it leave ConcurrentModificationException,
If there remains more than one item in the PQ in the second iteration, it gives the Exception but why not in one item remaining.

Thanks,
cmbhatt
Remko Strating
Ranch Hand

Joined: Dec 28, 2006
Posts: 893
Wel the code in the foreach syntax is looking for the second element in the PQ. This element doesn't exist because you have removed 3 of the 4 elements in you PQ and this element is now the first element.

You should never use the foreach syntax when you change the Arrays and Containers over with you're iterating. This could lead to unexpected behavior like this.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: PriorityQueue issue