The priority queue is another queue that differs from the FIFO queue. The element with the highest priority is removed from the queue each time.
Priorityqueue is a new data structure interface that is provided starting from JDK1.5.
If comparator is not provided, the elements in the priority queue are sorted by default in the natural order, that is, the numbers are small by default in the queue header, and the strings are sorted in dictionary order.
Because most of the information on the network will be priority queue each method attribute, there are few examples to explain, for the convenience of everyone later use, I wrote a demo~
If you want to implement a queue that is prioritized according to your wishes, you need to implement the comparator interface. The following method implements the establishment of a priority queue based on a variable.
Import Java.util.comparator;import Java.util.priorityqueue;import Java.util.queue;public class Test {private String name;private int population;public Test (String name, int population) {this.name = name; This.population = population;} Public String GetName () {return this.name;} public int getpopulation () {return this.population;} Public String toString () {return getName () + "-" + getpopulation ();} public static void Main (String args[]) {comparator<test> orderisdn = new comparator<test> () {public int compar E (Test O1, test O2) {//TODO auto-generated method Stubint Numbera = O1.getpopulation (); int numberb = O2.getpopulation (); I F (Numberb > Numbera) {return 1;} else if (Numberb<numbera) {return-1;} Else{return 0;}}; queue<test> priorityqueue = new priorityqueue<test> (11,ORDERISDN); Test T1 = new Test ("T1", 1), test t3 = new Test ("T3", 3), Test t2 = new test ("T2", 2), test T4 = new test ("T4", 0);p Riorityqueue. Add (T1);p riorityqueue.add (T3);p Riorityqueue.add (T2);p Riorityqueue.add (T4); System.out.println (Priorityqueue.poll (). toString ());}}
How to use the Priorityqueue priority queue in Java