java —— Comparable 接口和 Comparator 比较器

一、Comparable 接口

当一个自定义的类,比如 Student 需要存储在 TreeSet 集合当中,可以为 Student 实现 Comparable 接口。因为 TreeSet 集合内部的元素是自然排序,而系统根本不知道自定义的类如何排序,所以需要我们人为地定义排序方法,也就是对 Comparable 接口中的 compareTo 方法进行重写。

public class Student implements Comparable<Student>{

    String name;
    int num;
//构造方法
    public Student(String name,int num)
    {
        this.name=name;
        this.num=num;
    }
//get方法
    public String getName() 
    {
		return name;
	}

	public int getNum() 
    {
		return num;
	}
//重写Comparable接口中的compareTo方法
    @override
    public int compareTo(Student o)
    {
        int a=0;
    //比较num
        if(this.getNum()<o.getNum()){a=-1;}     
        else if(this.getNum()>o.getNum()){a=1;}
    //num相同的时候,比较name
        else {a=this.getName().compareTo(o.getName());}       
        return a;
    }
}
public static void main(String[] args)
{
    Student st1=new Student("aaa",11);
    Student st2=new Student("bbb",22);
    Student st3=new Student("ccc",22);
    TreeSet<Student> ts=new TreeSet();
    ts.add(st1);
    ts.add(st2);
    ts.add(st3);
    for(Student x:ts){System.out.println(x.getName());}
}

二、Comparator 比较器

上述情况中,如果 Student 不允许实现 Comparable 接口,可以另外定义一个 Comparator 比较器。如果既允许实现接口,又允许定义比较器,那么比较器的优先级大于接口。

public class Student implements Comparable<Student>{

    String name;
    int num;
//构造方法
    public Student(String name,int num)
    {
        this.name=name;
        this.num=num;
    }
//get方法
    public String getName() 
    {
		return name;
	}

	public int getNum() 
    {
		return num;
	}
}
public class StudentCompare implements Comparator<Student>{
    public int compare(Student o1,Student o2)
    {
     int a=0;
    //比较num
        if(this.getNum()<o.getNum()){a=-1;}     
        else if(this.getNum()>o.getNum()){a=1;}
    //num相同的时候,比较name
        else {a=this.getName().compareTo(o.getName());}       
        return a;
    }
}

Comparator 比较器实际上也是一个类,比如案例中的 StudentCompare 类,它要实现 Comparator 接口才能重写 Compare 方法。

  • 22
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值