PriorityQueue understand

1, not drawn out of the FIFO


Traditional queue is executed in FIFO order. The PriorityQueue is an absolute priority to

Low priority, first-out queue

 

2, how to sort


 

Since there PriorityQueue prioritize So how to sort.

Element a. Sorted into the queue implements Comparable interface in their natural order from small to large.

B. Comparator specified queue initialization when an external comparator.

PriorityQueue<String> queue1 = new PriorityQueue<>();
PriorityQueue<String> queue2 = new PriorityQueue<>(10);
PriorityQueue<String> queue3 = new PriorityQueue<>((a,b)->a.compareTo(b));

 

 

3, the internal structure


 

Internal storage array elements:

transient Object[] queue;

The default size array 11 (can be specified when initializing)  

 

Dynamic expansion mechanism

Capacity <64 expansion is 2 * n + 2, otherwise like ArrayList expanded to 1.5n

(A value of 64 is a sort of trade-off)

private void grow(int minCapacity) {
        int oldCapacity = queue.length;
        // Double size if small; else grow by 50%
        int newCapacity = oldCapacity + ((oldCapacity < 64) ?
                                         (oldCapacity + 2) :
                                         (oldCapacity >> 1));
        // overflow-conscious code
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        queue = Arrays.copyOf(queue, newCapacity);
    }

 

Small heap achieve root

Rootlets heap: complete binary tree is a parent node and satisfy no greater than about any one of the child nodes. (Note that left and right nodes are not ordered)

So vertex rootlets stack must be minimal (Comparator how to achieve the descending order, the designated reverse order to fetch)

Completely binary tree (all nodes satisfy not collapse node from left to right) is represented by an array.

PriorityQueue is to use an array to achieve a small heap root: meet each taking data is the smallest, but are not satisfied with the overall orderly .

 

 

 

Any node (as the array index n) can know the index value of its left and right child and parent nodes in the array:

Parent: (n-1) / 2

The left child node: 2n + 1

Right child: 2n + 2

  

Add or delete nodes on

By: Creating a complete binary tree in turn a new node, the new node then compared in turn with the parent, to meet the minimum requirements of the heap

Delete: Delete the last node with a node of a binary tree filled first, and then make adjustments.

Some nodes are most always get treated, because to meet the complete binary tree.

Many details of the Internet is no longer Detailed examples.

 

4, non-thread-safe


PriorityQueue thread-safe version: PriorityBlockingQueue, using ReentrantLock lock protection

 

Guess you like

Origin www.cnblogs.com/yangfei629/p/11567941.html