Use of Java comparer comparable and comparator

Source: Internet
Author: User

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

The comparer has a very large effect when sorting an array of objects

1, using the comparable interface, you need to rewrite the compareTo(T o) method, where the collation is defined, you can directly call Java.util.Arrays.sort () to sort the array of objects,

Example:

Package com.yaoxun.test;

public class Student implements comparable<student> {

	private int score;
	
	private int age;
	
	@Override public
	int compareTo (Student o) {
		if (This.score > O.score) return
			1;
		else if (This.score < o.score) 
			return-1;
		else {
			if (This.age > O.age) return
				1;
			else if (This.age < o.age) 
				return-1;
			else return
				0;}}}
	


2, using the comparator interface, you need to rewrite the compare(t O1, T O2) method,

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; }
    }
    
}




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.