Java中自定義物件使用Collections工具類中的Sort方法
阿新 • • 發佈:2019-01-09
Collections工具類中的sort方法有兩種形式:
(1) sort(List<T> list)
(2) sort(List<T> list, Comparator<? super T> c)
第一種方法中List型別的物件必須實現Comparable介面,此外,List中的元素必須可比較。
我們先定義類
package com.dongye.sort; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @author dongyewujiu * @date 19-1-9 * @description */ public class Person implements Comparable { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Person(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } @Override public int compareTo(Object o) { Person person = (Person) o; if(this.getAge()>person.getAge()){ return 1; }else if(this.getAge()<person.getAge()){ return -1; }else{ return 0; } } }
main方法進行sort方法的呼叫:
public static void main(String[] args) { Person person1 = new Person("德瑪",19); Person person2 = new Person("索拉卡",16); Person person3 = new Person("妖姬",17); List<Person> list = new ArrayList<>(); list.add(person1); list.add(person2); list.add(person3); Collections.sort(list); for (Person p:list){ System.out.println(p.toString()); } }
第二種方法的使用事先無需在自定義物件內部實現排序Comparable介面, 可以在外部實現排序介面Comparator :
public static void main(String[] args) { Person person1 = new Person("德瑪",19); Person person2 = new Person("索拉卡",16); Person person3 = new Person("妖姬",17); List<Person> list = new ArrayList<>(); list.add(person1); list.add(person2); list.add(person3); Collections.sort(list, new Comparator<Person>() { @Override public int compare(Person o1, Person o2) { if (o1.getAge() > o2.getAge()) { return 1; } else if (o1.getAge() < o2.getAge()) { return -1; } else { return 0; } } }); for (Person p:list){ System.out.println(p.toString()); } }