为什么 PriorityQueue 中的元素没有按自然顺序打印? [英] Why are elements in a PriorityQueue not printed in their natural ordering?

查看:56
本文介绍了为什么 PriorityQueue 中的元素没有按自然顺序打印?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 PriorityQueue 对字符串进行不同的排序?

Why PriorityQueue is sorting strings differently?

String[] sa = {">ff<", "> f<", ">f <", ">FF<", "> 2<", ">2 <", "> F<"};
PriorityQueue<String> q = new PriorityQueue<>();
for(String s : sa) {
    q.offer(s);
}
System.out.println("q : " +q);
Arrays.sort(sa);
System.out.println("sa : " +Arrays.toString(sa));

List<String> myList = Arrays.asList(sa);
Collections.sort(myList);
System.out.println("myList : " +myList);

它给了我:

q : [>2 <, >f<, >F<, >ff<, >FF<, >f <, >2 <]

q : [> 2<, > f<, > F<, >ff<, >FF<, >f <, >2 <]

sa : [>2 <, >F<, >f<, >2 <, >FF<, >f <, >ff<]

sa : [> 2<, > F<, > f<, >2 <, >FF<, >f <, >ff<]

我的列表:[>2 <, >F<, >f<, >2 <, >FF<, >f <, >ff<]

myList : [> 2<, > F<, > f<, >2 <, >FF<, >f <, >ff<]

但我期待:

q : [>2 <, >F<, >f<,>2<, >FF <, >f <,>ff<]

q : [> 2<, > F<, > f<, >2 < , >FF<, >f < , >ff< ]

请解释一下!!

推荐答案

来自 Javadocs:

方法 iterator() 中提供的 Iterator 不能保证以任何特定顺序遍历优先级队列的元素.如果您需要有序遍历,请考虑使用 Arrays.sort(pq.toArray()).

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()).

这意味着元素不一定以其自然顺序存储在队列中.所以如果你想按自然顺序获取元素,你必须单独排序或使用队列操作,例如:

This means that the elements are not necessarily stored in the queue in their natural ordering. So if you want to obtain the elements in their natural order, you have to sort separately or use the queue operations, e.g.,:

while( !q.isEmpty() ) {
    System.out.println(q.remove());
}

这篇关于为什么 PriorityQueue 中的元素没有按自然顺序打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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