Packagecode.test;ImportJava.util.Comparator;ImportJava.util.Iterator;ImportJava.util.PriorityQueue;ImportJava.util.Queue;/*** Experiments show that in Java: * 1. Priority queue Printing or iteration, the resulting output order is in the order of the heap structure array, roughly ordered but not fully guaranteed order * 2. Because heap ordering is an unstable sort, the elements do not remain in the original order when the precedence is the same. * Created by CG on 2017/9/7. */ Public classPriorityqueuetest { Public Static voidMain (string[] args) {Queue<Integer> queue =NewPriorityqueue<integer>(); Queue.add (1); Queue.add (5); Queue.add (3); Queue.add (2); Queue.add (8); Queue.add (10); Queue.add (23); Queue.add (14); System.out.println (queue); //output: [1, 2, 3, 5, 8, ten, Max.]Iterator<integer> Iterator =Queue.iterator (); while(Iterator.hasnext ()) {System.out.print (Iterator.next () )+ " "); }//Output: 1 2 3 5 8System.out.println (); Queue<Student> queue1 =NewPriorityqueue<student> (NewComparator<student>() {@Override Public intCompare (Student s1, Student S2) {returnS1.age-S2.age; } }); Queue1.add (NewStudent ("a", 14)); Queue1.add (NewStudent ("B", 12)); Queue1.add (NewStudent ("C", 12)); Queue1.add (NewStudent ("D", 12)); Queue1.add (NewStudent ("E", 12)); Queue1.add (NewStudent ("F", 13)); Queue1.add (NewStudent ("G", 11)); while(!Queue1.isempty ()) {System.out.println (Queue1.poll ()); } /*output g:11 c:12 d:12 e:12 b:12 f:13 a:14*/ }}classstudent{String name; intAge ; PublicStudent (String name,intAge ) { This. Name =name; This. Age =Age ; } @Override PublicString toString () {returnName + ":" +Age ; }}
Java Priority Queue Test