Collections集合工具类:用来对集合进行操作,部分方法如下
public static <T> void sort(List<T> list):将集合中元素按照默认规则排序
ArrayList<String> list = new ArrayList<>(); //往集合中添加一些元素 Collections.addAll(list,"q","f","g","d","e","s","w"); //默认排序 Collections.sort(list);//将集合中元素按照默认规则排序 System.out.println(list);
运行结果:
注意:
sort(List<T> list)使用前提
被排序的集合里边存储的元素,必须实现Comparable,重写接口中的方法compareTo定义排序的规则
public class Person01 implements Comparable<Person01> { private String name; private int age; public Person01() { } public Person01(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "Person01{" + "name='" + name + '\'' + ", 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(Person01 o) { // return 0; //默认的返回值 //自定义一个默认排序 // return this.getAge() - o.getAge();//升序排序 return o.getAge() - this.getAge();//降序排序 } }
ArrayList<Person01> pe = new ArrayList<>(); pe.add(new Person01("张三",15)); pe.add(new Person01("强强",10)); pe.add(new Person01("累加",20)); System.out.println(pe); //默认排序 Collections.sort(pe);//默认排序 System.out.println(pe);
运行结果:
在compateTo中
this-传递的参数就是升序
传递的参数 - this就是降序
public static <T> void sort(list<T> list,Comparator<? super T>);将集合中元素按照指定规则排序。
Comparator和Comparable的区别:
Comparable:自己(this)和别人(参数)比较,自己需要实现Comparable接口,重写比较的规则compareTo方法
Comparator:相当于找一个第三方,比较两个
当泛型是数据类型时:
public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(); list.add(9); list.add(2); list.add(8); list.add(7); System.out.println(list); //public static <T> void sort(list<T> list,Comparator<? super T>);将集合中元素按照指定规则排序。 Collections.sort(list, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o1 - o2;//升序 // return o2 - o1;//升序 } }); System.out.println(list); }
运行结果:
当泛型是对象时:
public class Student { private String name; private int age; @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } public Student() { } public Student(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; } }
public static void main(String[] args) { List<Student> list = new ArrayList<>(); list.add(new Student("张三",15)); list.add(new Student("李四",10)); list.add(new Student("王五",20)); System.out.println(list); //public static <T> void sort(list<T> list,Comparator<? super T>);将集合中元素按照指定规则排序。 Collections.sort(list, new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { return o1.getAge()-o2.getAge();//升序,反之就是倒序 } }); System.out.println(list); }
运行结果: