List<Integer> list= new arrayList<>(); list.add(3); list.add(1); list.add(56); list.add(21); Collections.sort(list); System.out.println(lsit.toString());//1 3 21 56默認升序
List<String> list = new ArrayList<>(); list.add("orange"); list.add("ob"); list.add("green"); list.add("yellow"); //進行排序 Collections.sort(list);//它是根據每一個字符的asi碼進行排序 System.out.println(list.toString());
int compare(T o1,T o2)比較用來排序的兩個參數 - o1<o2 返回負整數 - o1==o2 返回0 - o1>o2 返回正整數
package 集合排序; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class CatSort { public static void main(String[] args) { Cat cat1=new Cat("jom",25,"中華田園貓"); Cat cat2=new Cat("jerry",22,"加菲貓"); ArrayList<Cat> list = new ArrayList<>(); list.add(cat1); list.add(cat2); Collections.sort(list,new AgeComparator());//傳入排序的類和排序的規則 System.out.println(list); } } //按名字排序 class NameComparator implements Comparator<Cat>{ @Override public int compare(Cat o1, Cat o2) { //按照名字升序排序 return o1.getName().compareTo(o2.getName());//這裏的compareTo是比較字符串的大小的,返回狀況和compare同樣 } } //按年齡排序 class AgeComparator implements Comparator<Cat>{ @Override public int compare(Cat o1, Cat o2) { int age1=o1.getMonth(); int age2=o2.getMonth(); return age1-age2; } } class Cat{ private String name; private int month; private String species; public Cat(String name, int month, String species) { this.name = name; this.month = month; this.species = species; } //省略了get和set方法 @Override public String toString() { return "Cat[" + name + "," + month + "," + species + "]"; } }
對每一個類的對象總體進行排序,成爲天然排序java
類的comparaTo方法成爲天然比較方法ide
若是排序的是集合,調用Collections.sort()方法排序函數
若是排序的是數字,調用Arrays.sort()方法排序測試
編寫自定義類,實現Comparable接口this
實現comparaTo()方法code
編寫測試類,使用Collections.sort(排序集合)進行排序對象
public int compareTo(Goods o) {//將當前對象(調用它的對象)和傳入的對象進行比較 return (int) (this.price-o.getPrice()); }
package 集合排序; import java.util.ArrayList; import java.util.Collections; public class GoodsSort { public static void main(String[] args) { ArrayList<Goods> list = new ArrayList<>(); list.add(new Goods("s001","電冰箱",3200)); Collections.sort(list); System.out.println(list); } } class Goods implements Comparable<Goods>{ private String id; private String name; private double price; public Goods(String id, String name, double price) { this.id = id; this.name = name; this.price = price; } //省略了get和set方法 @Override public String toString() { return "Goods{" + "商品編號=" + id + ", 商品名稱='" + name + '\'' + ", 商品價格=" + price + '}'; } @Override public int compareTo(Goods o) { //根據商品的價格進行排序 return (int) (this.price-o.getPrice()); } }
補充:排序