1、Java自行實現 compareTo 方法的類能夠直接調用 Collections.sort 實現排序,如 String 類:String類實現了Comparable接口,並且compareTo方法底層是用C++封裝實現的,比較高效,咱們應該直接使用。Integer等基礎java
數據類型的包裝類也是如此。app
List<String> lists = new ArrayList<String>(); lists.add("6"); lists.add("5"); lists.add("10"); //lists中的對象String 自己含有compareTo方法,能夠直接調用sort方法,默認實現升序排序 Collections.sort(lists);
2、自定義的類通常有兩種方法實現排序:ide
實現 Comparable 接口。this
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 接口。code
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]