Java: strange order of queue made from priority queue

 ̄綄美尐妖づ 提交于 2019-12-02 04:04:26

The way you've implemented compare is wrong, and would only work if it's called only in a very specific way that you're assuming. However, you have no idea in what context the PriorityQueue actually calls compare. The compare function might well be called on an existing element inside the data structure, instead of the new one, or vice versa.

(Even if you did read the source code and traced it and found that this particular implementation works in a certain way, you shouldn't depend on that if you want your code to be maintainable. At the least, you'd be making yourself more work by having to explain why it works.)

You could just use some sort of counter and assign it as the value for each added item, then implement compare correctly based on the value.

A correct implementation of compare might look like this:

int compare(Object x, Object y){
    return x.getSomeProperty() - y.getSomeProperty();
}

Note that if you switch the order of the parameters, the answer will change as well. No, the int returned does not necessarily have to come from {-1, 0, 1}. The spec calls for 0, or a negative or positive integer. You can use any one you wish, so long as it's the correct sign.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!