PriorityQueue queue usage entry, priorityqueue queue
PriorityQueue is a type of Queue, which is called priority Queue. This class implements the Queue interface.
This is called priority queue because PriorityQueue implements the Comparator comparison interface, that is, PriorityQueue has a sorting method internally. In the process of offer (insert) or poll (pop-up) elements, data in the priority queue will be dynamically sorted (rather than explicitly calling the sorting method, which may be the case for beginners ).
If Comparator is not provided, PriorityQueue will be executed by default, that is, arranged by natural numbers. The smallest number has the highest priority. For strings, it is in the Lexicographic Order.
A priority queue is different from a regular queue. For a regular queue, each time a queue is entered from the end of the team, the first line is displayed. For a priority queue, each departure is the element with the highest priority.
Next, let's take a specific case to better understand the usage of PriorityQueue.
1 public static void main (String [] args) {2 // TODO Auto-generated method stub 3 Queue <Integer> queue = new PriorityQueue <Integer> (10, new Comparator <Integer> () {4 5 @ Override 6 public int compare (Integer I, Integer j) {7 // TODO Auto-generated method stub 8 // note, here the odd number is on the left, and the number is big on the left 9 int result = I % 2-j % 2; 10 if (result = 0) 11 result = I-j; 12 return result; 13} 14}); 15 for (int I = 0; I <10; I ++) 16 {17 queue. offer (I); 18} 19 for (int I = 0; I <10; I ++) 20 {21 System. out. println (queue. poll (); 22} 23}
The above code implements a comparator, which is set to the left of the even number and the left of the decimal number. Therefore, the output result is: 0 2 4 6 8 1 3 5 7 9.
If you want to swap the parameter I and j of the comparator, can you guess the result?
After the parameter is changed, the odd number is on the right side of the even number and the large number is on the right side of the decimal number (Note: I personally feel that the priority on the right side is the highest, that is, the right side is the first line, Do not spray ~);
public static void main(String[] args) { // TODO Auto-generated method stub Queue<Integer> queue=new PriorityQueue<Integer>(10,new Comparator<Integer>() { @Override public int compare(Integer j, Integer i) { // TODO Auto-generated method stub int result=i%2-j%2; if(result==0) result=i-j; return result; } }); for(int i=0;i<10;i++) { queue.offer(i); } for(int i=0;i<10;i++) { System.out.println(queue.poll()); } }
The print result is 9 7 5 3 1 8 6 4 2 0.