2

In my opinion, the biggest advantage of array is that we can access to any element with O(1). But a queue can only be accessed from the head or the tail.

Besides, PriorityBlockingQueue is a sorted collection, which means every single add operation will cause all larger(or smaller) elements to shift. That's quite expensive.

So I don't understand why not using a linked list instead.

2
  • 2
    Take a look into the heap data structure, which is backed by an array. PriorityBlockingQueue should use a similar strategy. Commented May 14, 2018 at 3:52
  • 2
    Suggested : search Implementation of Priority Queue using Heap and Implementing Min (or Max) Heap You will then know as why array is used (Heap is easy to implement using arrays and also it's efficient as it does not involve shifting of elements, it just involves assignment, swapping of elements {without shifting of elements at other indexes}, and access of elements at known index for comparison, these operations are efficient in an array) Commented May 14, 2018 at 4:01

2 Answers 2

4

Besides, PriorityBlockingQueue is a sorted collection, which means every single add operation will cause all larger(or smaller) elements to shift.

You misunderstood the inner workings of the PriorityBlockingQueue: it does not shift up or down the entire array; that would indeed be too expensive. Instead, it uses a data structure called heap, which uses an array for its storage, but does not apply "plain" indexing to it. Instead, it stores items in a tree-like way, making O(log2n) insertions and removals possible.

For details on how PriorityBlockingQueue maintains the heap see implementations of shiftDown and shiftUp in PriorityQueue.java.

Sign up to request clarification or add additional context in comments.

Comments

3

Because the underlying data structure is really a binary heap, which is most efficiently implemented via an array, and which in turn provides O(log(N)) performance on addition and removal. An LinkedList could not possibly be as efficient as a heap.

Besides, PriorityBlockingQueue is a sorted collection, which means every single add operation will cause all larger(or smaller) elements to shift.

No it won't. It will cause a re-heapify operation, which is considerably more efficient than what you describe.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.