The built-in iterator for java's PriorityQueue does not traverse the data structure in any particular order. Why?

后端 未结 5 1042
说谎
说谎 2020-11-22 08:43

This is straight from the Java Docs:

This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces.

5条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 09:24

    Well, as the Javadoc says, that's how it's been implemented. The priority queue probably uses a binary heap as the underlying data structure. When you remove items, the heap is reordered to preserve the heap property.

    Secondly, it's unwise to tie in a specific implementation (forcing a sorted order). With the current implementation, you are free to traverse it in any order and use any implementation.

提交回复
热议问题