directly on code:
Import java.util.ArrayList;
Import java.util.Collections;
Import Java.util.Comparator;
Import java.util.List; /** * * <p> * ClassName collectionssort * </p> * <p> * Description mainly introduces two kinds of sets of sorting algorithm <br/> * First : Java.util.Collections.sort (java.util.List), requiring that the sorted elements must implement the Java.lang.Comparable interface <br/> * Second: Java.util.Collections.sort (Java.util.List, Java.util.Comparator), this method requires the implementation of the Java.util.Comparator interface <br/> * Third: The following example uses a sort of int property, which can be sorted by using the following methods <br/> * public int compareTo (Cat o) {return this.getname (). CompareTo ( O.getname (0);}
<br/> * Fourth: Description of CompareTo () function <br/> * If result;<br/> * <0 a<b <br/>= * ==0 a==b;<br/>
* >=0 a>b; * </p> * * @author wangxu wangx89@126.com * <p> * Date 2014-9-16 Afternoon 04:52:57 * </p> * @version V1.0 * */public class Collectionssort {public static void main (string[] args) {//METHOD1 (); test first Method M ETHOD2 ()//test the second method} public static voidMethod1 () {list<cat> List = new arraylist<cat> ();
Cat C = new Cat ("A", 10);
List.add (c);
c = new Cat ("B", 20);
List.add (c);
c = new Cat ("C", 3);
List.add (c);
Ascending order output Collections.sort (list);
SYSTEM.OUT.PRINTLN (list);
Descending order output Collections.sort (list, Collections.reverseorder ());
SYSTEM.OUT.PRINTLN (list);
public static void Method2 () {list<cat> List = new arraylist<cat> ();
Cat C = new Cat ("A", 10);
List.add (c);
c = new Cat ("B", 20);
List.add (c);
c = new Cat ("C", 3);
List.add (c);
comparator<cat> catcomparator = new Cat ();
Ascending order output Collections.sort (list, catcomparator);
SYSTEM.OUT.PRINTLN (list);
Descending order Output Catcomparator = Collections.reverseorder (catcomparator);
Collections.sort (list, catcomparator);
SYSTEM.OUT.PRINTLN (list);
} class Cat implements Comparable<cat>, comparator<cat> {private int age;
private String name; Public cat () {} public cat (String name, int age) {THis.age = age;
THIS.name = name;
public int getage () {return this.age;
Public String GetName () {return this.name;
public void Setage (int age) {this.age = age;
public void SetName (String name) {this.name = name; //implementation of the comparable interface, do not override this method @Override the public int compareTo (Cat o) {//TODO auto-generated methods stub return thi
S.age-o.age; @Override public String toString () {//TODO auto-generated Method Stub return "name:" + getName () + ", Age:" + Getag
E (); //implementation of the comparator interface, which needs to be overridden @Override public int compare (cat O1, cat O2) {//TODO auto-generated method stub ret
Urn O1.getage ()-o2.getage ();
}
}