JAVA Comparator Interface Sort usage __java

Source: Internet
Author: User
Tags comparable stub java comparator

The Java comparator has two classes, namely the comparable interface and the comparator interface.

When sorting an array of objects , the comparator works very clearly, first of all, to explain the comparable interface.

Let the object that needs to be sorted implement the comparable interface, override the CompareTo (T O) method in which you define the collation, and then call Java.util.Arrays.sort () directly to sort the array of objects, as follows:

Class Student implements comparable<student>{private String name;
    private int age;
    
    private float score;
        Public Student (String name, int age, float score) {this.name = name;
        This.age = age;
    This.score = score;
    Public String toString () {return name+ "\t\t" +age+ "\t\t" +score; @Override public int compareTo (Student o) {//TODO auto-generated Method stub if (This.score&gt
            O.score)//score is private and why it can be invoked directly because within the student class return-1;//by the high end sort else if (this.score<o.score)
        return 1;
                else{if (this.age>o.age) return 1;//from bottom to high sort else if (this.age<o.age)
            return-1;
        else return 0; }} public class ComparableDemo01 {/** * @param args/public static void main (string[] args) {//TODO auto-generated method stub StuDent stu[]={new Student ("Zhangsan", 20,90.0f), New Student ("Lisi", 22,90.0f), New Student ("W
        Angwu ", 20,99.0f), New Student (" Sunliu ", 22,100.0f)};
        Java.util.Arrays.sort (Stu);
        for (Student s:stu) {System.out.println (s); }
    }
}
In the above program, the implementation of the comparable interface, and rewrite the CompareTo method, the students first by the results from large to small rankings, the same time according to age from low to high order.

The result of the execution is

Sunliu 22 100.0
Wangwu 20 99.0
Zhangsan 20 90.0
Lisi 22 90.0


However, when designing a class, you may not consider having the class implement the comparable interface, then you need to use a different comparator interface comparator.

From the above example, we can see that compareTo (t o) has only one parameter, and the Compare (T o1,t O2) that must be implemented in the comparator interface has two parameters.

Code instances

Package edu.sjtu.ist.comutil;

Import Java.util.Comparator;
    Class Student {private String name;
    private int age;
    
    private float score;
        Public Student (String name, int age, float score) {this.name = name;
        This.age = age;
    This.score = score;
    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;
    public float Getscore () {return score;
    public void SetScore (float score) {this.score = score;
    Public String toString () {return name+ "\t\t" +age+ "\t\t" +score; Class Studentcomparator implements comparator<student>{@Override public int compare (Student O1, Stud
    ent O2) {//TODO auto-generated Method stub if (O1.getscore () >o2.getscore ()) return-1;    else if (O1.getscore () <o2.getscore ()) return 1;
            else{if (O1.getage () >o2.getage ()) return 1;
            else if (O1.getage () <o2.getage ()) return-1;
        else return 0; }} public class ComparableDemo02 {/** * @param args/public static void Main (string[)
                args) {//TODO auto-generated method stub Student stu[]={new Student ("Zhangsan", 20,90.0f), New Student ("Lisi", 22,90.0f), New Student ("Wangwu", 20,99.0f), New Student ("Sunliu", 22,1
        00.0f)};
        Java.util.Arrays.sort (Stu,new studentcomparator ());
        for (Student s:stu) {System.out.println (s); }
    }

}
The above is still sorted on the student object array, using the Array.Sort method, which is different when implementing the comparator interface, the sort method needs to pass in two parameters, that is, the Stu object array, and the overridden implementation of the comparator comparison method class.

The result of the program running is the same as the above



Array.Sort is sorted by array, and if we don't want to use arrays, we want to use a set under the collection interface, and if we want to use the list, we need to make some changes:

Package comparatortest;
	/** * Defines a student class * including school number, name, Math score, language score * @author Zhangnan */public class student{private String Name;
	private int ID;
	private int scoremath;
	private int Scorechi; Public Student (String name,int id,int score1,int score2) {this.
		Name=name;
		This.id=id;
		This.scoremath=score1;
	This.scorechi=score2; Public String GetName () {return this.
	Name; } public void SetName (String pname) {this.
	Name=pname;
	public int GetID () {return this.id;
	public void SetID (int pID) {this.id=pid;
	public int Getmathscore () {return scoremath;
	public void Setmathscore (int score1) {this.scoremath=score1;
	public float Getchiscore () {return scorechi;
	public void Setchiscore (int score2) {this.scorechi=score2; /** * Back to student information/public String toString () {return integer.tostring (ID) + "\t\t" +name+ "\t\t" +integer.tostring (SCO
	Remath) + "\t\t" +integer.tostring (Scorechi); }
	
	
}
--------------------------------------------------------------------------------package comparatortest;

Import Java.util.Comparator; public class Comparatorsort implements Comparator {public int compare (Student s1, Student s2) {//TODO auto-generate
		D method Stub if (S1.getid () > S2.getid ()) {return 1;
		else if (S1.getid () < S2.getid ()) {return-1;
			else {if (S1.getmathscore () > S2.getmathscore ()) return-1;
			else if (S1.getmathscore () < S2.getmathscore ()) return 1;
		else return 0;

}}}--------------------------------------------------------------------------------package comparatortest;
Import java.util.ArrayList;
Import java.util.Collections;

Import Java.util.Random; public class Test {public static void main (string[] args) {//TODO auto-generated method stub Random random=new Ra
		Ndom ();
		ArrayList st=new ArrayList ();
		Student s1= New Student ("Zhangnan1", Random.nextint (Ten), Random.nextint (M), Random.nextint (100)); Student s2= New Student ("Zhangnan2", Random.nextint(a), Random.nextint (M), Random.nextint (100));
		Student s3= New Student ("Zhangnan3", Random.nextint (Ten), Random.nextint (M), Random.nextint (100));
		Student s4= New Student ("Zhangnan4", Random.nextint (Ten), Random.nextint (M), Random.nextint (100));
		St.add (S1);
		St.add (S2);
		St.add (S3);
		St.add (S4);
		SYSTEM.OUT.PRINTLN ("All Students:");
		Collections.sort (St,new comparatorsort ());
		for (Student s:st) {System.out.println (s);

 }

	}

}
The overridden compare methods are sorted by randomly generated student IDs, followed by mathematical results, resulting in:

All the students:

0 ZHANGNAN3 67 78

0 zhangnan2 39 0

2 Zhangnan1 57 96

3 Zhangnan4 62 53 Here We do not use an array of objects, we use the ArrayList collection under the collection interface, so the sort is in collections.sort (st,new Comparatorsort ())



Related Article

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.