java比较器(1)

可以直接用Arrays进行数组的排序操作,但对象所在的类必须实现Comparable

Comparable<T>{

comparaTo<T o>();

}

注释:此方法返回一个int类型的数据,此数据只能为三个值:1(表示大于),-1(表示小于),0(表示等于)


package com.compara;

import java.util.Arrays;

public class ComparableDemo01 {
		public static void main(String[] args) {
			Student[] stu = {
					new Student("张三",50,90.0f),
					new Student("李四",40,93.0f),
					new Student("王五",30,94.0f)
			};
			Arrays.sort(stu);
			for (int i = 0; i < stu.length; i++) {
				System.out.println(stu[i].toString());
			}
		}
	
}
/**
 * 继承Comparable
 * @author Administrator
 *description:先比较得分,年龄相同的按照年龄比较
 */
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;
	}
	
	/**
	 * 重写数组的toString()方法
	 */
	public String toString(){
		return name + "\t\t" + this.age + "\t\t" + this.score;
	}
	
	@Override
	public int compareTo(Student o) {//重写compareTo方法
		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;
			}
		}
		
	}
	
}
通过修改返回1还是-1就可以实现对student数组的排序。

原理:比较器的排序就是二叉树的排序算法。排序的基本原理,使用第一个元素作为根节点,如果后面的内容比根节点要小,则

放在左子树,如果比根节点要大,则放在右子树。最后遍历节点得到从左到右、从小到大的排序结果。如下图所示:



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值