標籤:stat ons dem util 使用 import 因此 super nbsp
1 package com.iotek.set; 2 3 import java.util.ArrayList; 4 import java.util.Collections; 5 import java.util.Comparator; 6 import java.util.List; 7 /** 8 * 9 * 對ArrayList容器中的內容進行排序: ArrayList中儲存多個Person對象(具有name,age,id屬性),10 * 要求按照年齡從小到大排序,年齡相等的話再按照名字的自然順序來排序輸出11 * 思路:12 * 使用ArrayList來儲存Person對象,使用Collections類所提供的靜態方法sort來按照要求對13 * ArrayList進行排序,然後輸出排序好的資訊。14 * @author Administrator15 *16 */17 public class CollectionsDemo2 {18 /* 1.建立一個ArrayList容器19 * 2.建立一個Person類,具有name,age,id屬性20 * 3.對容器中的資料排序,用Collections類的方法sort對List介面的實作類別排序21 * 4.輸出排序好的內容 */22 23 public static void main(String[] args) {24 List<Personc> data = new ArrayList<Personc>();25 data.add(new Personc("jack",20,10));26 data.add(new Personc("rose",10,7));27 data.add(new Personc("mary",30,6));28 data.add(new Personc("zhang",50,18));29 data.add(new Personc("jay",20,11));30 Collections.sort(data, new Comparator<Personc>() {31 @Override32 public int compare(Personc o1, Personc o2) {33 // 首先按年齡來排序34 if(o1.getAge() - o2.getAge() > 0) {35 return 1;36 } else if(o1.getAge() - o2.getAge() < 0) {37 return -1;38 } else { //年齡相等時,再按照名字來進行排序,39 /*具體的字串是String類的執行個體化對象,可以調用String類的40 * compareTo(String anotherString)方法來對字串按照字典順序進行排序41 */ return o1.getName().compareTo(o2.getName()); 42 }43 }44 });45 46 for(Personc p : data) {47 System.out.println(p.toString());48 }49 }50 51 }52 /* sort(List<T> list, Comparator<? super T> c) 根據指定比較子產生的順序對指定列表進行排序53 * Comparator<? super T> c c表示一個比較子,比較子可以用匿名內部類來實現54 * 匿名內部類產生的是個介面的實作類別對象,因此要實現這個介面中的compare()方法 */55 /*String.compareTo(String anotherString) 按字典順序比較兩個字串,返回一個int類型的值*/56 57 class Personc {58 private String name;59 private int age;60 private int id;61 public Personc(String name, int age, int id) {62 super();63 this.name = name;64 this.age = age;65 this.id = id;66 }67 public String getName() {68 return name;69 }70 public void setName(String name) {71 this.name = name;72 }73 public int getAge() {74 return age;75 }76 public void setAge(int age) {77 this.age = age;78 }79 public int getId() {80 return id;81 }82 public void setId(int id) {83 this.id = id;84 }85 @Override86 //重寫toString方法,定義列印格式87 public String toString() {88 return "Person [name=" + name + ", age=" + age + ", id=" + id + "]";89 }90 91 }
ht-7 對arrayList中的自訂對象排序