Java comparator comparable interface and comaprator Interface

Source: Internet
Author: User
Tags java comparator

Java comparator has two types: comparable interface and comparator interface.

When sorting an array of objects, the comparator plays an obvious role. First, we will explain the comparable interface.

Implement the comparable interface for the objects to be sorted, override the compareto (t o) method, and define the sorting rules in it, then you can directly call Java. util. arrays. sort () to sort the object array. The example is as follows:

View code

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" + age + "\ t" + score ;} @ override public int compareto (student O) {// todo auto-generated method stub if (this. score> O. score) // The score is private. why can it be called directly? This is because the return-1 in the student class; // sort 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 ;}} 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 ("wangwu", 20, 990000f), new student ("sunliu", 22,100.0 f)}; Java. util. arrays. sort (Stu); For (student s: Stu) {system. out. println (s );}}}

Program running result:

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

However, when designing a class, we often do not consider implementing the comparable interface for the class, so we need to use another comparator interface comparator.

From the above example, we can find 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 example:

View code

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, Student 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,100.0f)};        java.util.Arrays.sort(stu,new StudentComparator());        for(Student s:stu)        {            System.out.println(s);        }    }}

The running result of the above program is the same as that of code instance 1.

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.