Very similar to the implementation of Qsort in C + +, building a new comparison object comparator can
Import java.util.arraylist;import java.util.collections;import java.util.comparator;class Student{public int age; private string Name;public Student (String Name,int age) {this.age=age;this.name=name;} Public String toString () {string str=name+ ' is ' +age;return str;}} public class Sort{public static void Main (string[] args) {arraylist<student> s=new arraylist<student> (); S.add (New Student ("CJC")), S.add (New Student ("Jake", +)), S.add (New Student ("John"), S.add ("New Student" ("Alice") , 23)); SYSTEM.OUT.PRINTLN ("The Order before sorting!"); System.out.println (s);//The elements in the collection are sorted by age Collections.sort (S,new Comparator () {@Overridepublic int compare (Object O1, Object O2) {//TODO auto-generated method stubstudent stu1= (Student) O1; Student stu2= (Student) O2;return stu2.age-stu1.age;}); SYSTEM.OUT.PRINTLN ("The Order after sorting!"); System.out.println (s);}}
Java ArrayList sorting based on storage objects