两者都可用来在定义比较方法,然后用在排序中。
Comparable是类本身继承的接口
Comparator实在类外定义一个排序的类
比较而言,觉得Comparator更灵活一些,但是Comparable方便一些。
举个栗子:
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class Main { public static void main(String[] args) { ArrayList<Pair> list = new ArrayList<>(); list.add(new Pair(8, 1)); list.add(new Pair(6, 5)); list.add(new Pair(6, 3)); list.add(new Pair(5, 7)); list.add(new Pair(4, 9)); // 用Comparator排序 -- 按照两个数的和排序 list.sort(new PairComparator()); for (Pair p: list) System.out.println(p); System.out.println(); // 用Comparable排序 -- 先按第一个数排序 再按第二个数排序 Collections.sort(list); for (Pair p: list) System.out.println(p); } } class PairComparator implements Comparator<Pair> { @Override public int compare(Pair p1, Pair p2) { int sum1 = p1.getSum(); int sum2 = p2.getSum(); return (sum1 == sum2 ? 0 : (sum1 < sum2 ? -1 : 1)); } } class Pair implements Comparable<Pair> { private int first; private int second; public Pair(int first, int second) { this.first = first; this.second = second; } @Override public int compareTo(Pair p) { if (first == p.first) { if (second == p.second) return 0; return second < p.second ? -1 : 1; } return first < p.first ? -1 : 1; } public int getSum() { return first + second; } public String toString() { return "[first:" + first + ", second:" + second + ", sum:" + getSum() + "]"; } }
输出:
[first:8, second:1, sum:9] [first:6, second:3, sum:9] [first:6, second:5, sum:11] [first:5, second:7, sum:12] [first:4, second:9, sum:13] [first:4, second:9, sum:13] [first:5, second:7, sum:12] [first:6, second:3, sum:9] [first:6, second:5, sum:11] [first:8, second:1, sum:9]
对于一些已经写好的类,比如String,我们当然不能去修改它的compareTo()方法,于是可以写一个自定义的比较器。
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class Main { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("abcd"); list.add("bcd"); list.add("cd"); list.add("d"); Collections.sort(list); System.out.println(list); list.sort(new MyStringComparator()); System.out.println(list); } } // 自定义的String排序方法 按字符串长度排序 class MyStringComparator implements Comparator<String> { @Override public int compare(String o1, String o2) { int len1 = o1.length(); int len2 = o2.length(); return (len1 == len2 ? 0 : (len1 < len2 ? -1 : 1)); } }
输出:
[abcd, bcd, cd, d] [d, cd, bcd, abcd]
时间: 2024-08-03 19:30:15