Compareble 接口与Comparator接口比较

Compareble接口

     可以直接通过Arrays.sort 对数组进行排序

import java.util.Arrays;

public class Student implements Comparable<Student> 
{
	private String name;
	private int age;
	private int score;

	public Student(String name, int age, int score) {
		super();
		this.name = name;
		this.age = age;
		this.score = score;
	}
  
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + ", score=" + score
				+ "]";
	}

	@Override
	public int compareTo(Student o) {
		// TODO Auto-generated method stub
		if (this.age < o.age) {
			return -1;
		}
		if (this.age > o.age) {
			return 1;
		} else {
			if (this.score < o.score) {
				return -1;
			}
			if (this.score > o.score) {
				return 1;
			}

		}

		return 0;
	}
      public static void main(String[] args) {
		Student  stu[]={
				new Student("马超", 68, 88),
				new Student("赵云", 30, 90),
				new Student("关二个", 33, 99),
				new Student("张飞",32, 92)
		};
		Arrays.sort(stu);
		for (int i = 0; i < stu.length; i++) {
			System.out.println(stu[i]);
		}
	}
}
输入结果 Student [name=赵云, age=30, score=90]
Student [name=张飞, age=32, score=92]
Student [name=关二个, age=33, score=99]
Student [name=马超, age=68, score=88]
如果 Student类没有实现comparable 则会抛出Student cannot be cast to java.lang.Comparable (student类不能被抛到java.lang.Comparable )说明arrays.sort()实现是根据compareble进行数组排序的。引用一老兄的话:java中的对象排序永远都是以Comparable 接口为标准的。、



另一种比较器 comparator  

comparator接口中实现的方法

compare(T o1,To2)---比较用来比较的2个参数

compare 主要作用是用来对已经写好的类,但是没有实现comparable 接口进行的补充。

http://blog.csdn.net/cz1029648683/article/details/6666855  一位老兄的文章。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值