collections - Java : PriorityQueue queue results and natural ordering -
collections - Java : PriorityQueue queue results and natural ordering -
i know, queue follow fifo(first in first out) order, not sure why next output appears below java sample program
java sample
public static void main(string args[]) { queue<string> q = new priorityqueue<string>(); q.add("3"); q.add("1"); q.add("2"); iterator<string> itr = q.iterator(); while (itr.hasnext()) { system.out.println(itr.next() + " "); } } output :
1 3 2 as per java doc of java.util.priorityqueue.priorityqueue()
creates priorityqueue default initial capacity (11) orders elements according natural ordering. q1) body please explain why output 1 3 2 , how natural order works here.
q2) have checked natural ordering , related comparable/comparor doesn't sorting(ascending/descending) order only??
the priorityqueue in java datastructure, sorts elements contains. excerpt javadoc:
the elements of priority queue ordered according natural ordering, or comparator provided @ queue construction time, depending on constructor used.
the problem unordered output comes iterator implementation. excerpt, time iterator() method:
returns iterator on elements in queue. iterator not homecoming elements in particular order.
so don't java fixed order iterator. if utilize poll() method in loop given elements in ascending order.
if looking queue in fifo-sense may have @ linkedlist , utilize addfirst() , getlast() methods.
java collections queue order
Comments
Post a Comment