Inherited Comparable interface, and implement the compareTo () method;
Instead of specifying a specific comparator when using java.util.Arrays.sort () method, sort () method uses the object's own comparison function to sort objects
For example
Entry
3
1 3 -5
-2 4 1
Export
-5 1 3 //升序排序
4 1 -2 //降序排序
sum = -25
import java.util.Arrays;
import java.util.Scanner;
public class 比较器 {
private static class Node implements Comparable<Node>{
int a;
public Node(int s) {
this.a = s;
}
@Override
public int compareTo(Node o) {
// TODO Auto-generated method stub
return o.a - this.a; //实现降序排序
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
for(int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
Node[] b = new Node[n]; //创建一个类数组
for(int i = 0; i < n; i++) {
int c = sc.nextInt();
b[i] = new Node(c);
}
Arrays.sort(a); //默认是升序排序
Arrays.sort(b); //自定义比较器,实现降序排序
int sum = 0;
for(int i = 0; i < n; i++) {
sum += a[i] * b[i].a;
}
System.out.println(sum);
}
}