1. Comparator
from large to small:
static Comparator<Integer> comparator2 = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
};
PriorityQueue<Integer> queue = new PriorityQueue<>(comparator2);
queue.add(5);
queue.add(10);
queue.add(2);
queue.add(4);
while(!queue.isEmpty()){
System.out.println(queue.poll());
}
Output:
From small to large:
static Comparator<Integer> comparator2 = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
};
Output:
2. Comparable
custom classes are sorted from small to large:
class Person implements Comparable<Person>{
String name;
int age;
public Person(String name,int age){
this.name = name;
this.age = age;
}
@Override
public int compareTo(Person o) {
return this.age - o.age;
}
}
PriorityQueue<Person> queue = new PriorityQueue<>();
queue.add(new Person("w20",20));
queue.add(new Person("w10",10));
queue.add(new Person("w40",40));
queue.add(new Person("w30",30));
while(!queue.isEmpty()){
System.out.println(queue.poll().name);
}
Output:
Custom classes sorted from large to small:
class Person implements Comparable<Person>{
String name;
int age;
public Person(String name,int age){
this.name = name;
this.age = age;
}
@Override
public int compareTo(Person o) {
return o.age - this.age;
}
}
Output:
Summary:
The difference between Comparator and Comparable is:
1. When comparing, Comparator needs to pass two parameters, so that they can compare and return the required one, while Comparable only needs one parameter, and then use certain data (you can It is a member variable of the class, or it can be a certain value or variable) and is compared with the passed parameters
2. Therefore, when comparing, Comparator belongs to the external comparator, and Comparable belongs to the internal comparator.
PriorityQueue The priority queue will be used in the algorithm:
such as: leetcode373. Find the sum of the smallest K pairs of numbers
To construct the object, you can use:
the data type of the incoming queue data and the comparator (the comparison rules are defined by yourself)
PriorityQueue<Integer> queue = new PriorityQueue<>(comparator2);
You can also directly pass in a data type that implements the Comparator or Comparable interface.
PriorityQueue<Person> queue = new PriorityQueue<>();