默认是升序排序
只能传List集合不能传Set集合
自定义类型要重写接口的实现类中的compareTo方法,并且只能在实现类中重写,不能使用匿名内部类重写
package Collections; public class Person implements Comparable<Person>{ private String name; private int age; public Person() { } public Person(String name, int age) { 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 int compareTo(Person person) { // 比较两个人的年龄 this和参数person return person.getAge() - this.getAge(); // return person.getAge() - this.getAge(); } }使用
Collections.sort(list1);自定义类型排序的第二种写法 使用匿名内部类重写其中的compare方法 ,且只能使用匿名内部类
两种方法的区别:
比较基本类型
比较自定义类型
多个条件判断 ,年龄相等按照姓名进行排序
package Collections; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class TestMain { public static void main(String[] args) { ArrayList<Integer> list1 = new ArrayList<>(); Collections.addAll(list1,4,5,8,9,7,5,2,5,7); System.out.println(list1); // 默认是升序排序 Collections.sort(list1); System.out.println(list1); ArrayList<Person> list2 = new ArrayList<>(); list2.add(new Person("zhang",11)); list2.add(new Person("zhang",45)); list2.add(new Person("zhang",19)); System.out.println(list2); Collections.sort(list2, new Comparator<Person>() {// 传的是一个接口 需要覆盖重写compare方法 @Override public int compare(Person student, Person t1) { return student.getAge()-t1.getAge(); // 按照年龄升序排序 } }); System.out.println(list2); } }
