I read documentation and everything i could find about PriorityQueue, but still don’t get why output is so strange I mean I can’t get a point of adding order, can anyone explain?
PriorityQueue<String> pq = new PriorityQueue<String>();
pq.offer("2");
System.out.println("add 2 : " + pq);
pq.offer("4");
System.out.println("add 4 : " + pq);
System.out.println(pq.peek() + " ");
pq.offer("1");
System.out.println("offer 1 : " + pq);
pq.offer("3");
System.out.println("add 3 : " + pq);
pq.remove("1");
System.out.println("remove 1 : " + pq);
Output:
add 2 : [2]
add 4 : [2, 4] <- why 4 goes there
offer 1 : [1, 4, 2] <- why 1 goes first
add 3 : [1, 3, 2, 4] <- why reorder
remove 1 : [2, 3, 4] <- again
PriorityQueueonly guarantees that the first element is the smallest.A binary heap only guarantees in each sub-heab (sub-tree) the root is the smallest element.
The heap is actually a complete-tree (or an array representation of it). Whenever you insert an element that violates the condition (is smaller then the root), the old root is sifted down. this is done recursively over the heap.
This partial ordering allows fast and relatively cache-efficient (with array representation) data structure that can be used if you only need the min element at each point at time.