Java class Ordering

Source: Internet
Author: User

Reference Document: Java sort: Comparator vs comparable Getting Started

Java classes often face sorting problems, and as far as I know: Java offers two ways to compare comparable and comparator:

1. The comparable method requires a sorted class to inherit the comparable interface, overriding the CompareTo function, but only one method of comparison (overriding CompareTo once) can be implemented, for example:

The class definition is as follows:

classStudentImplementsComparable<student> {    PrivateString name; PrivateString Key; Private floatscore; Private intAge ;  PublicStudent (string key, string name,floatScore,intAge ) {         This. Key =key;  This. Name =name;  This. score =score;  This. Age =Age ; } @Override/*public int CompareTo (Student ano) {if (This.score < ano.score) return-1;        if (This.score > Ano.score) return 1;            else {if (This.age > Ano.age) return 1;            if (This.age < ano.age) return-1;        else return 0; }//else}//compareto*/     Public intCompareTo (Student ano) {return(int)( This. Score-Ano.score); }}

You can see that CompareTo is rewritten by us, and then we can run the sort and then observe the results of the run:

        Student stus[] = {new Student ("Lee", "9527", 22,80)                ,new Student ("Zhang", "1839", 23,83 )                ,new Student ("Zhao", "1284", 21,80)};        Print (stus);        Arrays.sort (stus);        System.out.println ("after sorted:");        Print (stus);

The results of the operation are as follows:

Student{name= ' 9527 ', key= ' Lee ', score=22.0, age=80}student{name= ' 1839 ', key= ' Zhang ', score=23.0, age=83  }student{name= ' 1284 ', key= ' Zhao ', score=21.0, age=80}after sorted:student{name= ' 1284 ', key= ' Zhao ', score=21.0, age=80}student{name= ' 9527 ', key= ' Lee ', score=22.0, age=80}student{name= ' 1839 ', key= ' Zhang ', score=23.0, age=83}

Extension: Sorts the list of elements that are custom classes, and the custom list is defined as follows:

    Public StaticList<student>getstudents () {List<Student> col =NewArraylist<student>(); Random Rand=NewRandom ();        String Valkey; intValage, Valscore;        String ValName;  for(inti = 0; I < 10; i++) {Valkey=Uuid.randomuuid (). toString (); ValName= Randomstringutils.random (10, 20, 110,true,true); Valage= Rand.nextint (80); Valscore= Rand.nextint (80); Col.add (NewStudent (Valkey,valname, Valage, Valscore)); }        returnCol; }

Sort by the Collections.sort (List) method:

List<student> grade = student.getstudents ();        Iterator<Student> iter = grade.iterator ();        Collections.sort (grade);          while (Iter.hasnext ()) {            //iter.next ();             System.out.println (Iter.next (). toString ());        }

2. Sometimes we need to sort multiple keywords, then we need to implement java.util.Comparator, we can sort the class student any field. We do not need to change the class student, the class itself does not implement Java.lang.Comparable or Java.util.Comparator interface, the code is as follows:

class Implements Comparator<student> {    publicint  Compare (Student st1, Student st2) {         return  st1.getname (). CompareTo (St2.getname ());}    }

Next we test by sequencing, we must use the Collections.sort (list, Comparator) method instead of the Collections.sort (list) method:

 Public classClasssort { Public Static voidMain (String []args) {//Student stu1 = new Student ("Wen", 90, 17); //Student stu2 = new Student ("Mike", 90, 18); //System.out.print ("res:" + stu1.compareto (STU2));List<student> grade =student.getstudents (); Iterator<Student> iter =Grade.iterator (); //Collections.sort (grade);Collections.sort (Grade,Newstudsortbyname ());  while(Iter.hasnext ()) {//Iter.next ();System.out.println (Iter.next (). toString ()); }        /*Student stus[] = {new Student ("Lee", "9527", 22,80), New Student ("Zhang", "1839", 23,83), NE        W Student ("Zhao", "1284", 21,80)};        Print (Stus);        Arrays.sort (Stus);        System.out.println ("after sorted:");        Print (Stus); */    }     Public Static voidprint (Student [] stus) { for(inti = 0; i < stus.length; i++) {System.out.println (stus[i].tostring ()); }    }}

Note The executable code is as follows:

 Packagecomparable;ImportJava.util.*;Importorg.apache.commons.lang3.RandomStringUtils;ImportOrg.apache.commons.lang3.builder.Diff;/*** Created by Carl on 11/7/15.*/classStudentImplementsComparable<student> {    PrivateString name; PrivateString Key; Private floatscore; Private intAge ;  PublicStudent (string key, string name,floatScore,intAge ) {         This. Key =key;  This. Name =name;  This. score =score;  This. Age =Age ; } @Override/*public int CompareTo (Student ano) {if (This.score < ano.score) return-1;        if (This.score > Ano.score) return 1;            else {if (This.age > Ano.age) return 1;            if (This.age < ano.age) return-1;        else return 0; }//else}//compareto*/     Public intCompareTo (Student ano) {return(int)( This. Score-Ano.score); }     Public StaticList<student>getstudents () {List<Student> col =NewArraylist<student>(); Random Rand=NewRandom ();        String Valkey; intValage, Valscore;        String ValName;  for(inti = 0; I < 10; i++) {Valkey=Uuid.randomuuid (). toString (); ValName= Randomstringutils.random (10, 20, 110,true,true); Valage= Rand.nextint (80); Valscore= Rand.nextint (80); Col.add (NewStudent (Valkey,valname, Valage, Valscore)); }        returnCol; }     PublicString GetName () {returnname; }     Public floatGetscore () {returnscore; }     Public intGetage () {returnAge ; } @Override PublicString toString () {return"student{" + "name=" + name + ' \ ' + ", key= ' + key + ' \ ' +", score= "+ S Core + ", age=" + Age + '} '; }}//StudentclassStudsortbynameImplementsComparator<student> {     Public intCompare (Student st1, Student st2) {returnst1.getname (). CompareTo (St2.getname ()); }} Public classClasssort { Public Static voidMain (String []args) {//Student stu1 = new Student ("Wen", 90, 17); //Student stu2 = new Student ("Mike", 90, 18); //System.out.print ("res:" + stu1.compareto (STU2));List<student> grade =student.getstudents (); Iterator<Student> iter =Grade.iterator (); //Collections.sort (grade);Collections.sort (Grade,Newstudsortbyname ());  while(Iter.hasnext ()) {//Iter.next ();System.out.println (Iter.next (). toString ()); }        /*Student stus[] = {new Student ("Lee", "9527", 22,80), New Student ("Zhang", "1839", 23,83), NE        W Student ("Zhao", "1284", 21,80)};        Print (Stus);        Arrays.sort (Stus);        System.out.println ("after sorted:");        Print (Stus); */    }     Public Static voidprint (Student [] stus) { for(inti = 0; i < stus.length; i++) {System.out.println (stus[i].tostring ()); }    }}

Sorting Java Classes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.