package com.itheima.demo05.Collections; public class Student { private String name; private int age; public Student() { } public Student(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "Student{" + "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; } }
com.itheima.demo05.Collections Package; Import of java.util.ArrayList; Import java.util.Collections; Import java.util.Comparator; / * - java.utils.Collections is a collection of tools for the collection operation. Part follows: public static <T> void Sort (List <T> List, Comparator <Super T?>): The set of elements according to an specified rules. The difference Comparator and Comparable Comparable: own (this) and others (parameters) comparison, they need to implement the Comparable interface, rewrite the rules of comparison compareTo method Comparator: find the equivalent of a third-party referee to compare two Comparator collations: o1-o2: ascending order * / public class Demo03Sort { public static void main (String [] args) { the ArrayList <Integer> = new new list01 the ArrayList <> (); list01.add (. 1); list02.add (new Student ( "B Yang Mi"18)); list01.add (. 3); list01.add (2); System.out.println (list01); // [. 1,. 3, 2] the Collections.sort (list01, new new Comparator <Integer> () { // Comparative rewrite rules @Override public int Compare (O1 Integer, Integer O2) { // return O1-O2; // ascending return o2-o1; // descending } }); System.out.println (list01); the ArrayList <Student> = new new list02 the ArrayList <> (); list02.add (new new Student ( "A Dilly Reba", 18 is)); list02.add (new new Student ( "Gülnezer Bextiyar", 20 is)); list02.add (new new Student ( "Yang Mi" ,. 17)); System.out.println (list02); /*Collections.sort(list02, new new Comparator <Student> () { @Override public int Compare (Student O1, O2 Student) { // ascending order according to age return o1.getAge () - o2.getAge (); } } ); * / // expansion: understanding the Collections.sort (list02, new new Comparator <Student> () { @Override public int Compare (Student O1, O2 Student) { // ascending order according to age int result = o1.getAge () -o2.getAge (); // if two people of the same age, then use the name of the first word comparator IF (Result == 0) { Result = o1.getName () the charAt (0) -o2.getName (). .charAt (0); } return result; } }); System.out.println(list02); } }