This article describes the implementation of Java's ArrayList sorting function according to storage objects. Share it for your reference, as follows:
It is very similar to the implementation of qsort in c++. Just build a new comparison object Comparator.
package demo;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;class Stu{ public int age; private String name; public Stu(String name,int age){ this.age=age; this.name=name; } public String toString(){ String str=name+"is "+age; return str; }}public class Sort{ @SuppressWarnings({ "unchecked", "rawtypes" }) public static void main(String[] args){ ArrayList<Stu> s=new ArrayList<Stu>(); s.add(new Stu("cjc",25)); s.add(new Stu("jake",17)); s.add(new Stu("john",30)); s.add(new Stu("Alice",23)); System.out.println("Wulin.com test results:"); System.out.println("The order before sorting!"); System.out.println(s); //Sort the elements in the collection with more ages Collections.sort(s,new Comparator(){ @Override public int compare(Object o1, Object o2) { // TODO Auto-generated method stub Stu stu1=(Stu)o1; Stu stu2=(Stu)o2; return stu2.age-stu1.age; } }); System.out.println("The order after sorting!"); System.out.println(s); }}Running results:
PS: Here is a demonstration tool for your reference:
Online animation demonstration insert/select/bubble/merge/hill/quick sorting algorithm process tool:
http://tools.VeVB.COM/aideddesign/paixu_ys
For more information about Java algorithms, readers who are interested in this site can view the topics: "Java Data Structure and Algorithm Tutorial", "Summary of Java Operation DOM Node Tips", "Summary of Java File and Directory Operation Tips" and "Summary of Java Cache Operation Tips"
I hope this article will be helpful to everyone's Java programming.