java比较器实现

  1. 继承Comparable接口,并实现compareTo()方法;
  2. 在使用java.util.Arrays.sort()方法时不用指定具体的比较器,sort()方法会使用对象自己的比较函数对对象进行排序

举例

输入

3
1 3 -5
-2 4 1

输出

-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);
	}

}
发布了19 篇原创文章 · 获赞 0 · 访问量 318

猜你喜欢

转载自blog.csdn.net/weixin_43588422/article/details/104081001