import java.util.ArrayList;标签:sort,java,s1,list,add,Collections,public From: https://blog.51cto.com/u_10028442/5824710
import java.util.Collections;
import java.util.List;
/*
* 1.Collections.sort(list);只能对List排序,注意:list中的
* 元素类型必须具备可比较性(继承Comparable)
2.Collections.sort(list,new StrLenComparator());//指定比较器升序
*/
public class CollectionsTest {
public static void main(String[] args) {
sortDemo();
}
public static void sortDemo(){
List<String> list=new ArrayList<String>();
list.add("aasd");
list.add("aaa");
list.add("aaa");
list.add("dd");
list.add("ss");
list.add("gg");
System.out.println(list.toString());
Collections.sort(list);//默认升序
System.out.println(list.toString());
Collections.sort(list,new StrLenComparator());//指定比较器升序
System.out.println(list.toString());
}
}
//**************************************************************
import java.util.Comparator;
public class StrLenComparator implements Comparator<String>{
@Override
public int compare(String s1, String s2) {
// TODO Auto-generated method stub
if(s1.length()>s2.length()){
return 1;
}
if(s1.length()<s2.length()){
return -1;
}
return s1.compareTo(s2);
}
}