[java]代码库
1.
package s0223排序比较器_推荐使用comparator;
//排序比较的2种实现方法
//1. 实体类 java.lang.Comparable Comparato
//2.自定义比较器,implements java.util.Comparator,然后重写compare()方法
public class Comparator1 implements java.util.Comparator<String> {
public int compare(String o1, String o2) {
int len1=o1.length();
int len2=o2.length();
return len1-len2;
}
}
2.
package s0223排序比较器_推荐使用comparator;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String [] args){
String[] str={"a","abcd","abc","def"};
List<String> list=Arrays.asList(str);
System.out.println("排序前:"+list);
// Collections.sort(list);
Collections.sort(list,new Comparator1());//对指定列表排序,使用指定比较器 ,这里是从小到大排序
System.out.println("排序后"+list);
}
}