• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

PriorityQueue issue

 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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 ]
 
Remko Strating
Ranch Hand
Posts: 893
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 893
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic