10 Replies Latest reply on Jul 29, 2008 6:28 PM by 795426

    Why does an Iterator of PriorityQueue not iterate in sorted order?

      hi, I'm studying toward the SCJP exam, so I don't have much pragmatic realworld experience with the Collection classes. Most of it seem well thought out, but the following I cannot see any meaning to:

      Quote from the PriorityQueue API:
      "The Iterator provided in method iterator() is not guaranteed to traverse the elements of the PriorityQueue
      in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()). "

      What's the thinking behind the decision of this design? Why will an Iterator of an otherwise sorted PriorityQueue will not iterate in sorted order?

      It has ramifications for other methods that base themselves on the iterator, like toArray (won't create an array with elements in the same order as the PriorityQueue) and toString (won't return a string with elements in the same order as they are in the PriorityQueue). (Took me ages to source the problem back to the iterator, thinking that the error had to be in the logic of my Comparators)

      Other collections have Iterators that returns things in the same order as they are in the collection: I can call toString or toArray on an ArrayList and it will return elements in order.

      Using Arrays.sort(pq.toArray()) as the API suggest, looks fishy to me, as I loose any parameterised typing there might have been associated with the PriorityQueue - alas, It'll force me to mix generic and non-generic code.

      Can anyone enlighten me on this design? When is it GOOD to have iterators that return otherwise sorted collections in whatever order they like?

      Edited by: krzn on Jul 29, 2008 12:50 PM