Comparable接口

本文介绍了一个使用Java实现的学生对象数组排序的例子。通过实现Comparable接口,文章详细展示了如何自定义排序规则,先按照学生的成绩从高到低排序,当成绩相同时再按照年龄从低到高排序。

java.util.Arrays类也可以对Object数组进行排序,但是要使用这种方法排序必须实现Comparable接口,此接口就是用于指定对象排序规则的。

 

 

设计一个学生类,成绩由高到低排序,成绩相等,按年龄由低到高排序。

//=================================================
// File Name       :	Array_demo
//------------------------------------------------------------------------------
// Author          :	Common

// 类名:student_
// 属性:
// 方法:
class student_ implements Comparable<student_>{
	private String name;
	private int age;
	private float score;
	
	public student_(String name, int age, float score) {
		super();
		this.name = name;
		this.age = age;
		this.score = score;
	}

	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + ", score=" + score + "]";
	}
	
	public int compareTo(student_ stu){		//覆写compareTo()方法,实现排序规则的应用
		if(this.score>stu.score){
			return -1;
		}else if(this.score<stu.score){
			return 1;
		}else{
			if(this.age>stu.age){
				return 1;
			}else if(this.age<stu.age){
				return -1;
			}else{
				return 0;
			}
		}
	}
	
}

//主类
//Function        : 	Comparable_demo
public class Comparable_demo {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		student_ stu[] = {new student_("张三",20,90.0f),new student_("李四",22,90.0f),
				new student_("王五",20,99.0f),new student_("赵六",20,70.0f),
				new student_("孙七",22,100.0f)};
		java.util.Arrays.sort(stu);
		for(int i=0;i<stu.length;i++){
			System.out.println(stu[i]);
		}
	}

}

 

转载于:https://www.cnblogs.com/tonglin0325/p/5270161.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值