Principle and example analysis of priority queue in Java
This article mainly introduces the principle analysis of Java priority queue. It is introduced in great detail through the example code, which has a certain reference value for everyone's study or work. Friends in need can refer to it
1、 Priority queue overview
PriorityQueue is the implementation of the queue interface, which can sort the elements,
You can put wrapper classes of basic data types (such as integer, long, etc.) or custom classes
For wrapper classes of basic data types, the default order of elements in the priority queue is ascending
However, for self-defined classes, you need to define your own comparator
2、 Common methods
3、 Use of priority queues
1. The queue stores the wrapper class of basic data type
//自定义比较器,降序排列 static Comparator<Integer> cmp = new Comparator<Integer>() { public int compare(Integer e1,Integer e2) { return e2 - e1; } }; public static void main(String[] args) { //不用比较器,默认升序排列 Queue<Integer> q = new PriorityQueue<>(); q.add(3); q.add(2); q.add(4); while(!q.isEmpty()) { System.out.print(q.poll()+" "); } /** * 输出结果 * 2 3 4 */ //使用自定义比较器,降序排列 Queue<Integer> qq = new PriorityQueue<>(cmp); qq.add(3); qq.add(2); qq.add(4); while(!qq.isEmpty()) { System.out.print(qq.poll()+" "); } /** * 输出结果 * 4 3 2 */ }
2. The queue stores user-defined classes
//矩形类 class Node{ public Node(int chang,int kuan) { this.chang=chang; this.kuan=kuan; } int chang; int kuan; } public class Test { //自定义比较类,先比较长,长升序排列,若长相等再比较宽,宽降序 static Comparator<Node> cNode=new Comparator<Node>() { public int compare(Node o1,Node o2) { if(o1.chang!=o2.chang) return o1.chang-o2.chang; else return o2.kuan-o1.kuan; } }; public static void main(String[] args) { Queue<Node> q=new PriorityQueue<>(cNode); Node n1=new Node(1,2); Node n2=new Node(2,5); Node n3=new Node(2,3); Node n4=new Node(1,2); q.add(n1); q.add(n2); q.add(n3); Node n; while(!q.isEmpty()) { n=q.poll(); System.out.println("长: "+n.chang+" 宽:" +n.kuan); } /** * 输出结果 * 长: 1 宽:2 * 长: 2 宽:5 * 长: 2 宽:3 */ } }
3. Priority queue traversal
The iterator () of PriorityQueue does not guarantee that the queue elements are traversed in any particular order.
If you want to traverse in a specific order, first turn the queue into an array, and then sort the traversal
Example
Queue<Integer> q = new PriorityQueue<>(cmp); int[] nums= {2,5,3,4,1,6}; for(int i:nums) { q.add(i); } Object[] nn=q.toArray(); Arrays.sort(nn); for(int i=nn.length-1;i>=0;i--) System.out.print((int)nn[i]+" "); /** * 输出结果 * 6 5 4 3 2 1 */
4. Description of descending sequence of comparator
Comparator<Object> cmp = new Comparator<Object>() { public int compare(Object o1,Object o2) { //升序 return o1-o2; //降序 return o2-o1; } };
The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.