这两个方法经常搞混淆,现对其进行总结以加深记忆。
1. compareTo(Objecto)方法是java.lang.Comparable<T>接口中的方法,当需要对某个类的对象进行排序时,该类需要实现Comparable<T>接口的,必须重写public int compareTo(T o)方法,假设我们通过 x.compareTo(y) 来“比较x和y的大小”。若返回“负数”,意味着“x比y小”;返回“零”,意味着“x等于y”;返回“正数”,意味着“x大于y”。
2. compare(Objecto1,Object o2)方法是java.util.Comparator<T>接口的方法,它实际上用的是待比较对象的compareTo(Object o)方法
int compare(T o1, T o2) 是“比较o1和o2的大小”。返回“负数”,意味着“o1比o2小”;返回“零”,意味着“o1等于o2”;返回“正数”,意味着“o1大于o2”。
例一:compare方法实现数组的降序排序
package test;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
//先输入数组中元素的个数,然后输入数组中的元素
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
int N = in.nextInt();
Integer[] a = new Integer[N];
for (int i = 0; i < N; i++) {
a[i] = in.nextInt();
}
//对数组中元素进行排序,默认为升序排序,若想改为降序排序需要重写compare方法
Arrays.sort(a, new MyComparator());
//输出排序之后的结果
for (int i = 0; i < a.length; i++) {
if (i == a.length - 1)
System.out.print(a[i]);
else
System.out.print(a[i] + " ");
}
}
in.close();
}
}
class MyComparator implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
if (o1.intValue() < o2.intValue())
return 1;//返回正数意味着o1比o2大,与if条件相反,所以是降序排序
else if (o1.intValue() == o2.intValue())
return 0;
else
return -1;
}
}