好比將一個List<Student>
排序,則有兩種方式:
1:Student實現Comparable接口:
2:給排序方法傳遞一個Comparator參數:java
請看下面的舉例:
Student類:ide
package demo; //Student實現Comparable,須要實現compareTo方法 public class Student implements Comparable<Student>{ private String name; private Integer age; public Student(String name,Integer age) { // TODO Auto-generated constructor stub this.name=name; this.age=age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public int compareTo(Student o) { // TODO Auto-generated method stub if(this.age>o.getAge()){ return 1; } else if(this.age<o.getAge()){ return -1; } else{ return 0; } } }
主類:this
package demo; import java.util.*; public class main { public static void main(String[] args) { // TODO Auto-generated method stub List<Student> list=new ArrayList<Student>(); Student s1=new Student("T-F", 18); Student s2=new Student("H胡歌", 28); Student s3=new Student("Z周潤發", 50); Student s4=new Student("M梅蘭芳", 100); list.add(s1); list.add(s4); list.add(s3); list.add(s2); Iterator iterator=list.iterator(); System.out.println("------默認排序(按年紀)-------"); Collections.sort(list); while(iterator.hasNext()){ Student s=(Student)iterator.next(); System.out.println(s.getName()+" "+s.getAge()); } System.out.println("------倒序排序-------"); Comparator comparator=Collections.reverseOrder(); Collections.sort(list,comparator); Iterator iterator_reverse=list.iterator(); while(iterator_reverse.hasNext()){ Student s=(Student)iterator_reverse.next(); System.out.println(s.getName()+" "+s.getAge()); } System.out.println("------根據姓名排序-------"); Collections.sort(list,new Comparator<Student>(){ @Override public int compare(Student o1, Student o2) { // TODO Auto-generated method stub return o1.getName().compareTo(o2.getName()); }} ); Iterator iterator_name=list.iterator(); while(iterator_name.hasNext()){ Student s=(Student)iterator_name.next(); System.out.println(s.getName()+" "+s.getAge()); } } }
執行結果:
------默認排序-------
T-F 18
H胡歌 28
Z周潤發 50
M梅蘭芳 100
------倒序排序-------
M梅蘭芳 100
Z周潤發 50
H胡歌 28
T-F 18
------根據姓名排序-------
H胡歌 28
M梅蘭芳 100
T-F 18
Z周潤發 50code