A priority queue could work by sorting after each insertion, but it would be slow; each insertion would take time proportional to N*ln(N), where N is the size of the queue. But if you think about it, there's no reason for all the items in the queue to be sorted: you just need to know, at all times, which is the "first" item.

So instead, most priority queues use a data structure called a heap, which is a kind of partially-sorted binary tree. The tree is arranged so that every child node "below" a parent node in the tree would come after the parent if all the nodes were sorted; but the children of a parent aren't necessarily next if the tree were sorted. If you think about it, though, this means that the very first node in the sort is always at the root of the tree, and things are partially sorted as you move down the tree.

It turns out that after removing the root or adding a new child, you can restore the tree to a proper heap in ln(N) time, which is quite fast. This makes a heap an ideal data structure for implementing a priority queue.

Complex, really complex I must say. So, Could I assume that there's No way I could know how objects are arranged inside my PriorityQueue ? with this I mean an Easy way...?

I'm really worried I don't wanna be stuck with a question like that on the SCJP exam.

Thank you for the insights Ernest! They're always welcome.

You definitely don't need to understand how a PriorityQueue works internally for the SCJP exam. You might need to know that if you call toString() or if you iterate through the contents of the Queue, the order you get is not necessarily sorted by priority. Much like with a HashMap, if you iterate or call toString(), you can think of the results as being in random order. They're not really random, but the order is complicated and you don't really need to worry about it. Unless you're studying algorithms for, say, an algorithms class.

and just to be clear, the "heap" data structure is different from the "heap" memory pool. they are two separate concepts with the same name.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors

Jose Campana
Ranch Hand

Joined: May 28, 2007
Posts: 339

posted

0

Howdi!

I'm grateful for your responses, It's so cool to know more about the details of the language, I'll have to leave the internal algorithms for later though. And, I'm so relieved that questions about PriorityQueues in the SCJP exam, aren't as complicated as I imagined.

Have a nice day ! Keep up the fantastic work, Jose