1.
大きいものから小さいものまでのコンパレータ:
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());
}
出力:
小さいものから大きいものまで:
static Comparator<Integer> comparator2 = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
};
出力:
2. 比較可能な
カスタム クラスは、小さいものから大きいものへと並べられています。
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);
}
出力:
カスタム クラスを大きいものから小さいものに並べ替えます。
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;
}
}
出力:
概要:
Comparator と Comparable の違いは次のとおりです。
1. 比較する場合、Comparator は比較して必要なパラメータを返すために 2 つのパラメータを渡す必要がありますが、Comparable は 1 つのパラメータのみを必要とし、特定のデータを使用します (これはクラスのメンバー変数、または特定の値または変数) であり、渡されたパラメーター
2 と比較されます。 したがって、比較する場合、Comparator は外部コンパレーターに属し、Comparable は内部コンパレーターに属します。
PriorityQueue 優先キューは、leetcode373 などのアルゴリズムで使用されます。最小の K 個の数値ペアの合計を求めます。
オブジェクトを構築するには、
受信キュー データのデータ型とコンパレータ (比較ルールは自分で定義します) を使用できます。
PriorityQueue<Integer> queue = new PriorityQueue<>(comparator2);
Comparator または Comparable インターフェイスを実装するデータ型を直接渡すこともできます。
PriorityQueue<Person> queue = new PriorityQueue<>();