一、Java自行实现 compareTo 方法的类可以直接调用 Collections.sort 实现排序,如 String 类:String类实现了Comparable接口,而且compareTo方法底层是用C++封装实现的,比较高效,我们应该直接使用。Integer等基础
数据类型的包装类也是如此。
List<String> lists = new ArrayList<String>();
lists.add("6");
lists.add("5");
lists.add("10");
//lists中的对象String 本身含有compareTo方法,可以直接调用sort方法,默认实现升序排序
Collections.sort(lists);
二、自定义的类一般有两种方法实现排序:
实现 Comparable 接口。
public class Test implements Comparable<Test>{
private int order;
public int getOrder() {
return order;
}
public void setOrder(int order) {
this.order = order;
}
@Override
public int compareTo(Test t) { //根据序号对此对象进行排序
return new Integer(this.order).compareTo(new Integer(t.getOrder()));
}
}
2. 实现 Comparator 接口。
public class Apple {
private String appleName;
private String appleColor;
private String appleProvider;
public Apple(String appleName, String appleColor, String appleProvider) {
super();
this.appleName = appleName;
this.appleColor = appleColor;
this.appleProvider = appleProvider;
}
@Override
public String toString() {
return "appleName=" + appleName;
}
}
import java.util.Comparator;
public class Test implements Comparator<Apple> {
private int comparatorType;
/**
* comparatorType 为 0 ,根据 appleName 排序
* comparatorType 为1 ,根据 appleColor 排序
* comparatorType 为2 ,根据 appleProvider 排序
* @param comparatorType
*/
public Test(int comparatorType) {
this.comparatorType = comparatorType;
}
@Override
public int compare(Apple lhs, Apple rhs) {
if(0 == this.comparatorType)
return lhs.getAppleName().compareTo(rhs.getAppleName());
else if(1 == this.comparatorType)
return lhs.getAppleColor().compareTo(rhs.getAppleColor());
else if(2 == this.comparatorType)
return lhs.getAppleProvider().compareTo(rhs.getAppleProvider());
return 0;
}
}
public static void main(String[] args){
List<Apple> apples = new ArrayList<Apple>();
apples.add(new Apple("h", "b", "hd"));
apples.add(new Apple("a", "c", "gf"));
Collections.sort(apples, new Test(2));//根据供应商进行排序
System.out.println(apples.toString());
}
打印结果:[appleName=a, appleName=h]