先决条件: 优先级队列 , 比较器 优先级队列类似于常规队列,但每个元素都有一个与其关联的“优先级”。在优先级队列中,高优先级的元素优先于低优先级的元素。为此,它使用了一个比较函数,对元素进行总排序。
null
优先级队列的元素根据其自然顺序排序,或由队列构造时提供的比较器排序,具体取决于使用的构造函数 施工人员:
- public PriorityQueue(): 这将创建一个具有默认初始容量(11)的PriorityQueue,该队列根据元素的自然顺序对其进行排序。
- 公共优先队列(集合c): 这将创建一个PriorityQueue,其中包含指定集合(c)中的元素。如果指定的集合是SortedSet的实例,则该优先级队列将按照相同的顺序排序,否则该优先级队列将按照其元素的自然顺序排序。
- 公共优先队列(整数容量、比较器): 这将创建一个具有指定初始容量的PriorityQueue,该队列根据指定的比较器对其元素进行排序。
Parameters: capacity - the initial capacity for this priority queue comparator - the comparator that will be used to order this priority queue. If null, the natural ordering of the elements will be used.
- 公共优先队列(分拣集ss): 创建包含指定排序集中元素的PriorityQueue。该优先级队列将按照与给定排序集相同的顺序排序。
提供的示例代码说明了高优先级的学生(基于cgpa)在低cgpa的学生之前得到服务。
// Java program to demonstrate working of // comparator based priority queue constructor import java.util.*; public class Example { public static void main(String[] args){ Scanner in = new Scanner(System.in); // Creating Priority queue constructor having // initial capacity=5 and a StudentComparator instance // as its parameters PriorityQueue<Student> pq = new PriorityQueue<Student>( 5 , new StudentComparator()); // Invoking a parameterized Student constructor with // name and cgpa as the elements of queue Student student1 = new Student( "Nandini" , 3.2 ); // Adding a student object containing fields // name and cgpa to priority queue pq.add(student1); Student student2 = new Student( "Anmol" , 3.6 ); pq.add(student2); Student student3 = new Student( "Palak" , 4.0 ); pq.add(student3); // Printing names of students in priority order,poll() // method is used to access the head element of queue System.out.println( "Students served in their priority order" ); while (!pq.isEmpty()) { System.out.println(pq.poll().getName()); } } } class StudentComparator implements Comparator<Student>{ // Overriding compare()method of Comparator // for descending order of cgpa public int compare(Student s1, Student s2) { if (s1.cgpa < s2.cgpa) return 1 ; else if (s1.cgpa > s2.cgpa) return - 1 ; return 0 ; } } class Student { public String name; public double cgpa; // A parameterized student constructor public Student(String name, double cgpa) { this .name = name; this .cgpa = cgpa; } public String getName() { return name; } } |
输出:
Students served in their priority order Palak Anmol Nandini
注: 在需要定制排序的场景中,这种类型的优先级队列是首选的,即当需要不同的排序顺序时,可以定义自己比较实例的方式。如果存在更复杂的比较算法,例如多个字段等,则可以实现比较器。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END