這是一個接口,要讓對象擁有比較能力,那麼就能夠繼承這個接口,實現 compareTo 方法。java
comparaTo返回1則排在後面,返回-1排前面ide
public class Goods implements Comparable<Goods> { private String name; private int price; public Goods(String name, int price) { this.name = name; this.price = price; } @Override public int compareTo(Goods o) { if(this.price>o.price) return 1; else if(this.price<o.price) return -1; else return 0; } }
ArrayList<Goods> arr = new ArrayList<>(); arr.add(new Goods("a",22)); arr.add(new Goods("e",10)); arr.add(new Goods("b",99)); arr.add(new Goods("c",10)); Collections.sort(arr); //按price升序
var array = new Goods[4]; array[0] = new Goods("a",22); array[1] = new Goods("a",10); array[2] = new Goods("a",99); array[3] = new Goods("a",10); Arrays.sort(array); System.out.println(Arrays.toString(array));
Comparator至關於一個比較器,能夠對一類對象進行排序而無需繼承 Comparable 接口this
,能夠定製本身的排序器,只須要繼承 Comparator接口就行code
上面的 Goods 若是不想繼承 Comparable 排序接口,固然也能夠指定排序器對 ArrayList內置排序方法排序,指定排序規則對象
arr.sort(new Comparator<Goods>() { @Override public int compare(Goods o1, Goods o2) { return Integer.compare(o1.getPrice(),o2.getPrice()); //逆序 01 02位置換一下就是正序了 } });
固然 Comparator 也有本身定義的不少排序規則和不少排序方法。能夠結合 lambda表達式方便的排序排序
var ps = new Person[4]; ps[0] = new Person("bbc",10); ps[1] = new Person("ABAw",18); ps[2] = new Person("acd",1); ps[3] = new Person("Babe",10); Arrays.sort(ps, Comparator.comparing(Person::getName)); System.out.println(Arrays.toString(ps)); Arrays.sort(ps,Comparator.comparing(Person::getName,(s1,s2)->s1.length()-s2.length()).thenComparing(Person::getName)); //根據名字長度排序 相同則按字母排 Arrays.sort(ps,Comparator.comparingInt(p->p.getName().length())); System.out.println(Arrays.toString(ps)); System.out.println(Arrays.toString(ps));