Comparator接口
public interface Comparators <T> { int compare(T first, T second); } //要按长度比较字符串,可以如下定义一个实现 Comparator<String> 的类: class LengthComparator implements Comparator<String> { public int compare(String first, String second) { return first.length() - second.length(); } } //具体完成比较时,需要建立一个实例: Comparator<String> comp = new LengthComparator(); if (comp.compare(words[i], words[j]) > 0) ...
//要对一个数组排序,需要为 Arrays.sort 方法传人一个 LengthComparator 对象:
String[] friends = { "Peter", "Paul", "Mary" };
Arrays.sort(friends, new LengthComparator()):
另外Arrays.sort()的第二个参数可以使用lambda表达式替换
Arrays.sort(friends,(first,second)->first.length()-second.length();