Java常用接口:Comparable接口的实现与使用

本文将介绍Comparable接口以及,使用其对自定义对象比较大小和排序
下面是Comparable接口的声明以及作用,可以看到它可以使继承他的类进行比较大小,只需要调用实现类的compareTo方法即可

public interface Comparable< T >
This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class’s natural ordering, and the class’s compareTo method is referred to as its natural comparison method.

下面是这个compareTo的定义
在这里插入图片描述
就是告诉我们利用

目前对象.compareTo(需要比较的对象)

实现比较大小,

  • 如果返回值等于零:o1=o2
  • 返回值大于零则o1>o2
  • 返回值小于于零则o1<o2

接下来就是例子:

class P implements Comparable<P> {

	String name;
	int age;
	public P(String name,int age) {
		this.name = name;
		this.age = age;
	}
	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	}
	
	@Override
	public int compareTo(P o) {
		return this.age-o.age;
	}
}

他很类似Comparator,如果有兴趣可以参考java常用类:Comparator
只不过他是需要被我们要排序的类实现,如果我们想要排序一个自定义类,或者让一个自定义类可以比较大小就需要实现Comparable接口。上面写完了如何实现接口,下面说一下如何使用接口:

public class ComparableTest {

	public static void main(String[] args) {
		List<P> personList = new ArrayList<P>();
		personList.add(new P("ace",22));
		personList.add(new P("xb",21));
		personList.add(new P("glm",36));
		personList.add(new P("sxy",20));

		System.out.println("比较大小");
		P ace = new P("ace",22);
		P xb = new P("xb",21);
		String result = ace.compareTo(xb)==0?"一样大":ace.compareTo(xb)>0?"ace大":"xb大";
		System.out.println(result);
		
		System.out.println("按照年龄");
		Collections.sort(personList);
		for(P p:personList)
			System.out.println(p);
		System.out.println();
	}

}

在这里插入图片描述

Collections工具类可以对List这类继承Collection的类进行操作,之后我会写到

posted @ 2019-04-13 17:20  clay_ace  阅读(22645)  评论(0编辑  收藏  举报