java - PriorityQueue elements are not ordered -


why isnt output in ascending order?

public class test {      public static void main(string[] args) {         priorityqueue<edge> edges = new priorityqueue<edge>();         edges.add(new edge(1, 2, 23));         edges.add(new edge(2, 3, 1000));         edges.add(new edge(1, 3, 43));          iterator<edge> = edges.iterator();         while (i.hasnext())             system.out.println(i.next());     }   }  class edge  implements comparable<edge> {     private int v1;     private int v2;     private int w;       edge(int v1, int v2, int w) {         this.v1 = v1;         this.v2 = v2;         this.w = w;     }      public int getv1() {         return v1;     }       public int getv2() {         return v2;     }      public int getw() {         return w;     }      @override     public int compareto(edge o) {         return this.w - o.getw();     }      public string tostring() {         return ("v1: " + v1 + " v2: " + v2 + " w: " + w);     } } 

i tried using doing using list, , calling collections.sort(listtosort) , works. thought head of priorityqueue least element?

from docs ,

this class , iterator implement of optional methods of collection , iterator interfaces. iterator provided in method iterator() not guaranteed traverse elements of priority queue in particular order. if need ordered traversal, consider using arrays.sort(pq.toarray()).

note implementation not synchronized. multiple threads should not access priorityqueue instance concurrently if of threads modifies queue. instead, use thread-safe priorityblockingqueue class.

as @alejandro lucena stated , try toarray() method

hope helps !!


Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -