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.
ImportJava.util.Comparator;ImportJava.util.PriorityQueue;ImportJava.util.Queue; Public classTest {PrivateString name; Private intpopulation; PublicTest (String name,intpopulation) { This. Name =name; This. Population =population; } PublicString GetName () {return This. Name; } Public intgetpopulation () {return This. Population; } PublicString toString () {returnGetName () + "-" +getpopulation (); } Public Static voidMain (String args[]) {Comparator<test> orderisdn =NewComparator<test>(){ Public intCompare (Test O1, test O2) {//TODO auto-generated Method Stub intNumbera =o1.getpopulation (); intNumberb =o2.getpopulation (); if(Numberb >Numbera) { return1; } Else if(numberb<Numbera) { return-1; } Else { return0; } } }; Queue<test> Priorityqueue =NewPriorityqueue<test> (11, ORDERISDN); Test T1=NewTest ("T1", 1); Test T3=NewTest ("T3", 3); Test T2=NewTest ("T2", 2); Test T4=NewTest ("T4", 0); Priorityqueue.add (t1); Priorityqueue.add (T3); Priorityqueue.add (T2); Priorityqueue.add (T4); System.out.println (Priorityqueue.poll (). toString ()); }}
How to use the Priorityqueue priority queue in "Go" Java