Comparable与Comparator的使用

掌握比较器的排序原理

掌握Comparable与Comparator的使用

可以使用Arrays类中的方法对对象进行排序,但是数组中的所有元素都必须实现 Comparable 接口。

Comparable接口 定义如下

public interface Comparable<T>
public int compareTo(T o)
class Student implements Comparable<Student>
{
	private String name;
	private int age;
	private float score;
	public Student(String name,int age,float score){
		this.age=age;
		this.name=name;
		this.score=score;
	}
	public String toString(){
		return "姓名:"+this.name+"\n"+"年龄:"+this.age+"\n"+
			"分数:"+"\n"+this.score;
	}
	public int compareTo(Student stu){
		if(this.age<stu.age){
			return -1;
		}else if(this.age>stu.age){
			return 1;
		}else{
			if(this.score<stu.score){
				return -1;
			}else if(this.score>stu.score){
				return 1;
			}else{
				return 0;
			}
		}
	}
};
public class ComparableDemo01
{
	public static void main(String args[]){
		Student stu[]={new Student("张三",20,90.5f),new Student("小三",42,89.5f),
			new Student("大三",60,35.0f),new Student("一个人",34,34.9f)};
		java.util.Arrays.sort(stu);
		for(int i=0;i<stu.length;i++){
			System.out.println(stu[i]);
		}
	}
};
实际上比较器的排序原理就是,二叉排序算法

Comparator类
如果在开发的时候没有实现Comparable接口,则不能实现对象的排序操作,为解决这样的问题JAVA中定义了另外一个比较器Comparator接口
此接口定义如下
publci int compare(T o1,
            T o2)
public boolean equals(Object obj)


则上面的程序可以改成
import java.util.* ;
class Student{	// 指定类型为Student
	private String name ;
	private int age ;
	public Student(String name,int age){
		this.name = name ;
		this.age = age ;
	}
	public boolean equals(Object obj){	// 覆写equals方法
		if(this==obj){
			return true ;
		}
		if(!(obj instanceof Student)){
			return false ;
		}
		Student stu = (Student) obj ;
		if(stu.name.equals(this.name)&&stu.age==this.age){
			return true ;
		}else{
			return false ;
		}
	}
	public void setName(String name){
		this.name = name ;
	}
	public void setAge(int age){
		this.age = age ;
	}
	public String getName(){
		return this.name ;
	}
	public int getAge(){
		return this.age ;
	}
	public String toString(){
		return name + "\t\t" + this.age  ;
	}
};


class StudentComparator implements Comparator<Student>{	// 实现比较器
	public int compare(Student s1,Student s2){
		if(s1.equals(s2)){
			return 0 ;
		}else if(s1.getAge()<s2.getAge()){	// 按年龄比较
			return 1 ;
		}else{
			return -1 ;
		}
	}
};
在开发中尽量使用Comparable
使用Comparator需要单独建立排序的类,很不方便

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值