PriorityQueue 的顺序不对 [英] The order of the PriorityQueue is wrong

查看:114
本文介绍了PriorityQueue 的顺序不对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java 8 Intellij Idea中遇到了PriorityQueue的顺序问题,当我在队列中添加第三个数字时,顺序是错误的,但只有第三个有这个问题,这是我的代码.

I meet a problem about order of PriorityQueue in Java 8, Intellij Idea, when I add the third number in the queue, the order is wrong, but only the third one have this problem, here is my code.

import java.util.*;

public class vector {
    static Queue<Integer> q=new PriorityQueue<Integer>();
    public static void addNum(int num) {
        q.add(num);
    }
    public static void main(String args[]) {
        addNum(-1);
        addNum(-2);
        addNum(-3);
        addNum(-4);
        addNum(-5);
    }
}

我尝试调试代码,在addNum(-3)之后,队列是-3,-1,-2,但是在addNum(-4)之后,队列是-4,-3,-2,-1.

I try to debug the code, after addNum(-3), the queue is -3,-1,-2, but after addNum(-4), the queue is -4, -3, -2, -1.

推荐答案

PriorityQueue 的契约不保证迭代顺序,而是保证每个元素从优先级队列中移除将遵循队列类型的自然顺序,或者自定义比较器的顺序(如果提供).

The contract for PriorityQueue does not guarantee iteration order, but rather it guarantees that each element removed from the priority queue will follow either the natural ordering of the queue's type, or the ordering of a custom comparator, should one be provided.

Javadoc 评论了什么你看到的是:

The Javadoc comments on what you are seeing:

队列通常但不一定以 FIFO(先进先出)方式对元素进行排序.例外的是优先级队列,它根据提供的比较器或元素的自然顺序对元素进行排序,以及对元素进行 LIFO(后进先出)排序的 LIFO 队列(或堆栈).

Queues typically, but do not necessarily, order elements in a FIFO (first-in-first-out) manner. Among the exceptions are priority queues, which order elements according to a supplied comparator, or the elements' natural ordering, and LIFO queues (or stacks) which order the elements LIFO (last-in-first-out).

Java 似乎对优先队列强制执行的约定是,从队列中删除的第一个元素将遵循队列中对象的自然顺序,或者使用自定义比较器,应该是提供.

The contract which Java appears to enforce for priority queues is that the first element removed from the queue will follow the natural order of the object in the queue, or using a custom comparator, should one be provided.

如果我们添加到您当前的脚本中以删除添加的五个元素,我们将看到返回的项目将从最小到最大排序:

If we add to your current script to remove the five elements added, we will see that the items returned will be ordered from least to greatest:

public static void main(String args[]) {
    addNum(-1);
    addNum(-2);
    addNum(-3);
    addNum(-4);
    addNum(-5);

    // now remove all elements
    while (!q.isEmpty()) {
        System.out.println(q.remove());
    }
}

打印:

-5
-4
-3
-2
-1

如果你需要一个保持排序顺序的集合,那么考虑使用类似 TreeSet 的东西.或者,您可以使用常规的 ArrayList,然后调用 Collections.sort() 如果要强加特定顺序.

If you need a collection which maintains sorting order, then consider using something like TreeSet. Or, you could use a regular ArrayList, and then call Collections.sort() if you want to impose a certain order.

这篇关于PriorityQueue 的顺序不对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆