java - Does PriorityQueue maintain natural order? -


this question has answer here:

the elements of priority queue ordered according natural ordering, or comparator provided @ queue construction time, depending on constructor used.

however, in following example, when print whole queue @ once, queue's elements printed in random order. on other hand, if poll elements 1 one printed in natural order.

could explain me ambiguious behavior? or missing something?

public class queueexample {       public static class employee implements comparable<employee>{         private int id;         private string name;          public employee(int id, string name){             this.id=id;             this.name=name;         }          public string tostring(){             return "id:"+id+" name:"+name;         }          public int compareto(employee emp){             return name.compareto(emp.name);         }      }      public static void main(string[] args) {           queue<employee> priority=new priorityqueue<employee>();          priority.add(new employee(101, "atlas"));         priority.add(new employee(102, "ztlas"));         priority.add(new employee(101, "ftlas"));         priority.add(new employee(101, "ptlas"));          system.out.println(priority);          system.out.println(priority.poll());         system.out.println(priority.poll());         system.out.println(priority.poll());         system.out.println(priority.poll());      }  } 

output:

[id:101 name:atlas, id:101 name:ptlas, id:101 name:ftlas, id:102 name:ztlas]

id:101 name:atlas

id:101 name:ftlas

id:101 name:ptlas

id:102 name:ztlas

a bit further down in the documentation says:

the iterator provided in method iterator() not guaranteed traverse elements of priority queue in particular order.

since abstractcollection's tostring (which priorityqueue inherits) returns string in iteration order, no particular order it.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -