方法一:实现Comparable接口
package com.java.test; public class Person implements Comparable<Person> { private String name; private Integer age; public Person() { } public Person(String name, Integer age) { 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(Person o) { return age.compareTo(o.getAge());//正序
//return o.getAge().compareTo(age);//倒序
} }
package com.java.test; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class PersonTest { public static void main(String[] args) { List<Person> list = new ArrayList<Person>(); list.add(new Person("E", 16)); list.add(new Person("C", 14)); list.add(new Person("A", 12)); list.add(new Person("B", 13)); list.add(new Person("D", 15)); for (Person person : list) { System.out.println(person.getAge()); } System.out.println("####################"); Collections.sort(list); for (Person person : list) { System.out.println(person.getAge()); } } }
方法二:调用Collections.sort(List<T> list, Comparator<? super T> c),定义Comparator
package com.java.test; public class Person { private String name; private Integer age; public Person() { } public Person(String name, Integer age) { 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; } }
package com.java.test; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class PersonTest { public static void main(String[] args) { List<Person> list = new ArrayList<Person>(); list.add(new Person("E", 16)); list.add(new Person("C", 14)); list.add(new Person("A", 12)); list.add(new Person("B", 13)); list.add(new Person("D", 15)); for (Person person : list) { System.out.println(person.getAge()); } System.out.println("####################"); Collections.sort(list, new Comparator<Person>() { @Override public int compare(Person o1, Person o2) { return o1.getAge().compareTo(o2.getAge());//正序 //return o2.getAge().compareTo(o1.getAge());//倒序 } }); for (Person person : list) { System.out.println(person.getAge()); } } }
时间: 2024-10-10 18:59:09