java - Java优先级队列中的compareTo工作不稳定

标签 java

我在类里面使用的compareTo函数

public int compareTo(Book b) {  
    if(id>b.id){  
        return 1;  
    }else if(id<b.id){  
        return -1;  
    }else{  
    return 0;  
    }

}

当我添加一个优先级队列,其 id 顺序为 12 99 89 55 40 4 时,我得到的输出是:

4
40
12
99
55
89

我用来迭代 PriorityQueue 的代码是:

Iterator it = queue.iterator();
while(it.hasNext()){
  Book b = (Book)it.next();
  System.out.println(b.id);
}

这样的输出可能存在什么问题? 一旦我调用queue.remove()然后迭代,顺序似乎是正确的。

最佳答案

PriorityQueue 的迭代器不能保证按照元素类 (Book) 的 Comparable 实现定义的顺序返回元素)。

来自 PriorityQueue 的 Javadoc:

This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces. The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()).

关于java - Java优先级队列中的compareTo工作不稳定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44150690/

相关文章:

java - 为什么 PetClinic 示例中 Vets 类的 VetList 方法使用 XMLElement?

java - 如何设置只有秒和小数的倒计时器?

Java 使用 junit 检查

java - java中在构造函数中声明变量合法吗?例子

java - 如何在android中制作一个简单的设置页面?

java - 使用 MongoDB、Java 和 Jongo 创建动态查询

java - 使用 Java 中的 Regex 进行模式化并从未知形式中挑选出所需的值

java - 整数到随机数的稳定映射

java - 使用 readline 时 BufferedReader 不解析 ascii 控制字符

java - 是否可以使用 JSR 303 字段验证来验证 List<String> 值