Priorityqueue is a queue, which is called a priority queue, which implements the queue interface.
The priority queue is called because Priorityqueue implements the comparator comparison interface, which is the priorityqueue internally with a sort method, in the offer (insert) or poll (eject) element, The data in the priority queue is dynamically sorted ( not the explicit call ordering method, which may be considered by beginners ).
If comparator is not provided, the Priorityqueue will be executed by default, that is, according to the natural number, the smallest priority of the number is the highest, and for the string, it is in the dictionary order.
The priority queue differs from the regular queue, which is the first team to queue up from the end of the team, and for the priority queue, the highest priority element for each team.
Below, let's take a concrete case to understand Priorityqueue's usage more deeply.
1 Public Static voidMain (string[] args) {2 //TODO auto-generated Method Stub3Queue<integer> queue=NewPriorityqueue<integer> (10,NewComparator<integer>() {4 5 @Override6 Public intCompare (integer i, Integer j) {7 //TODO auto-generated Method Stub8 //attention to understanding, here is odd on the left, the number large on the left9 intresult=i%2-j%2;Ten if(result==0) Oneresult=i-J; A returnresult; - } - }); the for(inti=0;i<10;i++) - { - Queue.offer (i); - } + for(inti=0;i<10;i++) - { + System.out.println (Queue.poll ()); A } at}
The code above implements a comparator, which is set to the left of an even number of odd numbers on the left side of the decimal. The result is: 0 2 4 6 8 1 3 5 7 9
If, by exchanging the parameters I and J of the comparator, then, can the pro-students guess the result?
After the parameter interchange, the odd number on the right side of the even, large numbers on the right side of the decimal (note that the right side of the highest priority, that is, the right side is the team head, do not spray ~);
Public Static voidMain (string[] args) {//TODO auto-generated Method StubQueue<integer> queue=NewPriorityqueue<integer> (10,NewComparator<integer>() {@Override Public intCompare (integer j, integer i) {//TODO auto-generated Method Stub intresult=i%2-j%2; if(result==0) Result=i-J; returnresult; } }); for(inti=0;i<10;i++) {queue.offer (i); } for(inti=0;i<10;i++) {System.out.println (Queue.poll ()); } }
Printed result 9 7 5 3 1 8 6 4 2 0
Getting Started with Priorityqueue priority queue usage