java Comparable与Comparator

1、Comparable用法
Comparable指的是可比较的,使用方法是首先让待排序的类实现Comparable接口,并重写compareTo方法,然后调用Arrays.sort对目标对象进行排序。

public class UserBean implements Comparable<UserBean> {
        private String id;
        private String username;
        private String age;
        // 省略了  set and get 
        public int compareTo(UserBean o) {
               if(this.age > o.getAge()){
                    return 1;
               }else if(this.age < o.getAge()){
                     return -1
             }else{
                return 0;
             }
      }
}  

UserBean[] array = UserBean[3];
array[0] = new UserBean("1","zhangsan","11");
array[1] = new UserBean("2","lisi","12");
array[2] = new UserBean("3","wangwu","13");
Arrays.sort(array);

2、Comparator
实现comparator接口,将Comparator中的compare()方法进行重写,然后将comparator对象传入到arrays.sort()方法中

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);  
        }  
    }  
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值