標籤:
通過兩個例子實現對象的自訂排序
1、實現Comparator介面。
1 import java.util.ArrayList; 2 import java.util.Collections; 3 import java.util.Comparator; 4 import java.util.List; 5 6 public class StudentComparator implements Comparator<Object> 7 { 8 @Override 9 public int compare(Object arg0, Object arg1)10 {11 return ((Student)arg0).getId() - ((Student)arg1).getId();12 }13 14 public static void main(String[] args)15 {16 Student stu1 = new Student(11, "A");17 Student stu2 = new Student(33, "B");18 Student stu3 = new Student(22, "C");19 Student stu4 = new Student(55, "D");20 List<Student> stuList = new ArrayList<Student>(4);21 stuList.add(stu1);22 stuList.add(stu2);23 stuList.add(stu3);24 stuList.add(stu4);25 Collections.sort(stuList, new StudentComparator());26 System.out.println(stuList);27 }28 }29 30 class Student31 {32 private int id;33 34 private String name;35 36 public Student(int id, String name)37 {38 this.id = id;39 this.name = name;40 }41 42 public int getId()43 {44 return id;45 }46 47 public void setId(int id)48 {49 this.id = id;50 }51 52 public String getName()53 {54 return name;55 }56 57 public void setName(String name)58 {59 this.name = name;60 }61 62 public String toString()63 {64 return this.getId() + this.getName();65 }66 }
輸出:[11A, 22C, 33B, 55D]
2、在需要排序的類上直接實現Comparable介面
1 import java.util.ArrayList; 2 import java.util.Collections; 3 import java.util.List; 4 5 public class Student implements Comparable<Object> 6 { 7 private int id; 8 9 private String name;10 11 public Student(int id, String name)12 {13 this.id = id;14 this.name = name;15 }16 17 public int getId()18 {19 return id;20 }21 22 public void setId(int id)23 {24 this.id = id;25 }26 27 public String getName()28 {29 return name;30 }31 32 public void setName(String name)33 {34 this.name = name;35 }36 37 public String toString()38 {39 return this.getId() + this.getName();40 }41 42 @Override43 public int compareTo(Object o)44 {45 return this.getId() - ((Student)o).getId();46 }47 48 public static void main(String[] args)49 {50 Student stu1 = new Student(11, "A");51 Student stu2 = new Student(33, "B");52 Student stu3 = new Student(22, "C");53 Student stu4 = new Student(55, "D");54 List<Student> stuList = new ArrayList<Student>(4);55 stuList.add(stu1);56 stuList.add(stu2);57 stuList.add(stu3);58 stuList.add(stu4);59 Collections.sort(stuList);60 System.out.println(stuList);61 }62 63 }
同樣輸出:[11A, 22C, 33B, 55D]
3、一個類實現了Comparable介面則表明這個類自身對象之間是可以相互比較的,這個類對象組成的集合就可以直接使用sort方法排序。
Comparator可以看成一種演算法的實現,將演算法和資料分離。Comparator也可以在下面兩種環境下使用:
(1)類的設計師沒有考慮到比較問題而沒有實現Comparable,可以通過Comparator來實現排序而不必改變對象本身。
(2)可以使用多種排序標準,比如定義升序類、降序類等。
java學習(十六):對象的自訂比較,Comparator和Comparable