为什么 PriorityQueue 中的元素不按其自然顺序打印?
Why are elements in a PriorityQueue not printed in their natural ordering?
为什么 PriorityQueue
对字符串进行不同的排序?
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 <]
sa : [> 2<, > F<, > f<, >2 <, >FF<, >f <, >ff<]
myList : [> 2<, > F<, > f<, >2 <, >FF<, >f <, >ff<]
但我期待:
q : [> 2<, > F<, > f<, >2 < , >FF<, >f < , >ff< ]
求解释!!
来自Javadocs:
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()).
这意味着元素不一定按其自然顺序存储在队列中。所以如果你想获取自然顺序的元素,你必须单独排序或使用队列操作,例如:
while( !q.isEmpty() ) {
System.out.println(q.remove());
}
为什么 PriorityQueue
对字符串进行不同的排序?
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 <]
sa : [> 2<, > F<, > f<, >2 <, >FF<, >f <, >ff<]
myList : [> 2<, > F<, > f<, >2 <, >FF<, >f <, >ff<]
但我期待:
q : [> 2<, > F<, > f<, >2 < , >FF<, >f < , >ff< ]
求解释!!
来自Javadocs:
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()).
这意味着元素不一定按其自然顺序存储在队列中。所以如果你想获取自然顺序的元素,你必须单独排序或使用队列操作,例如:
while( !q.isEmpty() ) {
System.out.println(q.remove());
}