0

I want to loop through a PriorityQueue, and wondering if following iterator() is the best way

Iterator<MyObject> itr = queue.iterator();
while(itr.hasNext()){
  MyObject element = itr.next();
  // do sth
}

I suppose its time complexity would be O(1)?
I don't care about the queue afterwards, so another way would be to use poll() while !queue.isEmpty() but the time complexity would be O(logn).

waynewingorc
  • 169
  • 9

1 Answers1

1

If you want ordered retrieval of your elements, you must poll/remove elements from the queue; using iterator will not be enough.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413