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);
It gave me:
q : [> 2<, > f<, > F<, >ff<, >FF<, >f <, >2 <]
sa : [> 2<, > F<, > f<, >2 <, >FF<, >f <, >ff<]
myList : [> 2<, > F<, > f<, >2 <, >FF<, >f <, >ff<]
But I was expecting:
q : [> 2<, > F<, > f<, >2 < , >FF<, >f < , >ff< ]
Any explanation please!!
From the 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()).
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());
}