简体   繁体   English

比较器对于Priorityqueue Java无法正常工作

[英]Comparator not working correctly for Priorityqueue Java

I am adding edges to a PriorityQueue but for some reason they do not get sorted by their value, leading to a faulty result later. 我将边缘添加到PriorityQueue中,但是由于某些原因,它们没有按其值排序,从而导致稍后出现错误结果。

My edge class looks like this 我的边缘班看起来像这样

class Edge implements Comparable<Edge>{
int value;
String dest;
String start;

public Edge(String start, String dest, int g) {
    this.dest = dest;
    value = g;
    this.start = start;
}
@Override
public int compareTo(Edge o) {
    int temp = value - o.value;
    if (temp > 0) {
        return 1;
    }
    if (temp < 0) {
        return -1;
    }
    return 0;
}

Yet, when I run my code where I do addAll on a LinkedList belonging to the Node "Springfield, MO" to the PriorityQueue, the Edges get sorted in the wrong order as seen below, what is the issue? 但是,当我在属于“ Springfield,MO”节点的LinkedList上的addAll上运行代码,并将其添加到PriorityQueue时,Edges的排序顺序错误,如下所示,这是什么问题?

queue.addAll(list.get(node));

在此处输入图片说明

I have tried to make a specific comparator class for Edge and using it as a parameter in the PriorityQueue but I still get the same result. 我尝试为Edge创建一个特定的比较器类,并将其用作PriorityQueue中的参数,但仍然得到相同的结果。

The internal structure of the PriorityQueue is not ordered, it is a heap, you can check this question. PriorityQueue的内部结构不是有序的,它是一个堆,您可以检查问题。

When you retrieve data using method peek or poll , it is guranteed to be ordered. 使用方法peekpoll检索数据时,将保证将其排序。

But be careful when you iterator the queue: 但是在迭代队列时要小心:

The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order. 不保证方法iterator()中提供的Iterator以任何特定顺序遍历优先级队列的元素。 If you need ordered traversal, consider using Arrays.sort(pq.toArray()). 如果需要有序遍历,请考虑使用Arrays.sort(pq.toArray())。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM