类按照类中的某一个属性(或者多个属性)来对类的对象进行排序,
有 3 种方法可以实现,
1、Collections.sort 排序重写 compare方法
2、实现Comparable<T>接口
3、通过自定义比较器类的方式实现排序
以下,实现一个类的排序
class Person{ public String name; public int age; public Person(String name, int age) { super(); this.name = name; this.age = 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; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } }
一、Collections.sort 排序重写 compare方法
Collections.sort(List, new Comparator<Person>() { @Override public int compare(Person o1, Person o2) { return o1.getAge().compareTo(o2.getAge()); } });
二、实现Comparable<T>接口
class Person implements Comparable<Person>{ public String name; public int age; public Person(String name, int age) { super(); this.name = name; this.age = 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; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } @Override public int compareTo(Person o) { return this.getName().compareTo(o.getName()); } }
测试
public class T2 { public static void main(String[] args) { List<Person> list=new ArrayList<Person>(); Person p1=new Person("d",55); Person p2=new Person("c",18); Person p3=new Person("a",37); list.add(p1); list.add(p2); list.add(p3); sortPerson(list); } public static void sortPerson(List<Person> list){ Collections.sort(list);//编译通过; for (Person person : list) { System.out.println(person); } } }
输出
Person [name=a, age=37]
Person [name=c, age=18]
Person [name=d, age=55]
按照age属性排序,需要修改>compareTo方法
@Override public int compareTo(Person o) { return new Integer(this.getAge()).compareTo(o.getAge()); }
三、通过自定义比较器类的方式实现排序
// 自定义比较器:按name比较 class NameComparator implements Comparator<Person> { @Override public int compare(Person o1, Person o2) { return o1.getName().compareTo(o2.getName()); } } // 自定义比较器:按age比较 class AgeComparator implements Comparator<Person> { public int compare(Person object1, Person object2) {// 实现接口中的方法 return new Integer(object1.getAge()).compareTo(object2.getAge()); } }
测试
public class T2 { public static void main(String[] args) { List<Person> list=new ArrayList<Person>(); Person p1=new Person("d",55); Person p2=new Person("c",18); Person p3=new Person("a",37); list.add(p1); list.add(p2); list.add(p3); sortPerson(list); } public static void sortPerson(List<Person> list){ Collections.sort(list,new NameComparator()); for (Person person : list) { System.out.println(person); } } }
输出
Person [name=a, age=37]
Person [name=c, age=18]
Person [name=d, age=55]