java的Comparable接口详解

一、介绍

  在java中接口comparable使我们经常要接触到的,比如对集合或者数组进行排序,我们经常使用到Arrays.sort()或者Collections.sort().当集合中的对象是自定义的对象时,我们有两种方法能够使排序方法应用到自定义对象的集合(数组)中。下面我们介绍Comparable的用法。

二、java库提供的对象的排序

  下面是List中对Integer对象的排序
public class MainClass {
public static void main(String[] args) {
 List<Integer> list = new ArrayList<Integer>();
 Random rd = new Random();
 for(int i=0;i<10;i++)
   list.add(rd.nextInt(100));
 for(int i:list)
   System.out.print(i+" ");
 Collections.sort(list);
 System.out.println("");
 for(int i:list)
   System.out.print(i+" ");
}
}

这很简单,结果如下:

我们通过Integer的源码可以看出Integer类继承了Comparable接口

并且重写了compareTo,这也是Comparable中唯一的方法。

三、自定义对象的排序

  自定义对象同样需要继承Comparable接口,并重写compareTo方法,这里我们举一个比较学生成绩的Student类,如下:
class Student implements Comparable<Student>{
	int sno;
	int score;
	Student(int sno,int score){
		this.sno = sno;
		this.score = score;
	}
	@Override
	public int compareTo(Student o) {
		if(this.score<o.score) return -1;
		else if(this.score>o.score) return 1;
		else return 0;
	}
}

我们设本对象为A,比较的对象为B,用于比较的属性为x。在compareTo方法中,若A.x<B.x则返回-1,若A.x>B.x则返回1,相等的返回0。这里我们建议如果A.compareTo(B)==0,那么为了保证一致性A.equals(B)中最好也要为真(但这并不强制),可以根据实际情况决定是否重写equals(同样还有hashcode方法),这样在set或者map类型的集合中需药保证compareTo和equals的一致性。

执行的结果如下:

如果上面例子中的Student不继承成Comparable接口,程序会报错,编译通不过。这里我们需要注意一点的是只有继承了Comparable接口并重写了compareTo方法,这个类才视为Compareable类,如果值写了compareTo方法,没有明确implement Comparable则其只是一个普通的类

posted @ 2019-08-13 11:04  Mrfanl  阅读(31116)  评论(0编辑  收藏  举报