java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Comparable和Comparator的用法

关于Java中Comparable 和 Comparator的用法

作者:CrazyDragon_King

这篇文章主要介绍了关于Java中Comparable 和 Comparator的用法,Comparable 和 Comparator 是关于排序的两个接口,用来实现 Java 集合中的的排序功能,需要的朋友可以参考下

Comparable 和 Comparator

Comparable 和 Comparator 是Java的两个和排序相关的接口,又被称为 自然排序和定制排序。最近看了相关的内容,现在来记录以下自己的学习情况。
Comparable 和 Comparator 是关于排序的两个接口,用来实现 Java 集合中的的排序功能。具体作用可以查看 API 获取。

Comparable

这是API 文档中的简要介绍:

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. Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

用法:

需要排序实体类的实现 Comparable 接口,并重写 compareTo() 方法,就可以具有排序功能。某些会自动对元素进行排序的集合(如 TreeSet),当把元素放入集合中,就会自动调用 CompareTo() 方法进行排序(前提是元素必须实现这个接口)。但是其他的地方也可以使用的,不只是局限于 TreeSet,使用还是很广泛的。

Comparator

这是API 文档中的简要介绍:

A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don’t have a natural ordering.

用法:

Comparator 是一个第三方接口,具体用法是:设计一个比较器,创建一个类,实现这个接口,重写 compare() 方法。并且由于 Comparator 是一个函数式接口,可以使用 Lambda 表达式代替 Comparator 对象,使得代码更加简洁明了。

Talk is cheap, show me the code.

注意:博客中的内容可能不会很详细,所以想看的具体细节的,应该以书本和官方文档为主,这里的内容更多的是简单的介绍一下基本的用法。

测试实体类:Dog

public class Dog implements Comparable<Dog>{
	private String name;
	private int age;
	
	public Dog(String name, int age) {
		this.name = name;
		this.age = age;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
	@Override
	public String toString() {
		return "Dog [name=" + name + ", age=" + age + "]";
	}

	@Override
	public int compareTo(Dog dog) {
		return this.age > dog.age ? 1 : this.age < dog.age ? -1 : 0;
	}
}

测试实体类:Cat

public class Cat implements Comparable<Cat>{
	private String name;
	private Integer age;
	
	public Cat(String name, Integer age) {
		this.name = name;
		this.age = age;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	
	@Override
	public String toString() {
		return "Cat [name=" + name + ", age=" + age + "]";
	}

	@Override
	public int compareTo(Cat o) {
		//可以直接调用,这样更简单
		//调换 o.age 和 this.age 就是相反的顺序
		return o.age.compareTo(this.age); 
	}
}

测试类:Test

public class Test {
	public static void main(String[] args) {
		List<Dog> dogs = new LinkedList<>();
		List<Cat> cats = new LinkedList<>();
		
		dogs.add(new Dog("大黄",6));
		dogs.add(new Dog("大白",1));
		dogs.add(new Dog("小黑",5));
		dogs.add(new Dog("旺财",3));
		dogs.add(new Dog("二哈",2));
		
		cats.add(new Cat("牛牛",3));
		cats.add(new Cat("花咪",4));
		cats.add(new Cat("咪咪",10));
		cats.add(new Cat("小黄",2));
		cats.add(new Cat("大橘",6));
		
		//参数为 null 使用 自然排序,否则使用 定制排序
		//也可以看出来 定制排序 优先级高于 自然排序
		System.out.println("---------自然排序 升序--------");
		dogs.sort(null);   
		dogs.forEach(System.out::println);
		System.out.println("---------自然排序 降序--------");
		cats.sort(null);
		cats.forEach(System.out::println);
		
		//定制排序
	    //Comparator<Dog> c = (e1,e2)->e2.getAge() - e1.getAge();
		//dogs.sort(c) 这个就是下面这个的具体形式,
		//可以看出来参数是一个 Comparator 对象  
		System.out.println("---------定制排序 降序--------");
		dogs.sort((e1,e2)->e2.getAge() - e1.getAge());
		//流式API的简单的应用,效果和上面的类似,或者直接使用 forEacn 循环遍历
		dogs.stream().forEach(System.out::println);
		System.out.println("---------定制排序 升序--------");
	//	另一种遍历方式,可以看出来函数式编程非常灵活,我也是初学,觉得很神奇。
		cats.stream()
		.sorted((e1,e2)->e1.getAge()-e2.getAge())
		.forEach(System.out::println);
	}
}

运行截图:

运行截图

补充说明:list.sort()方法
API 文档中的描述:

Sorts this list according to the order induced by the specified Comparator.
All elements in this list must be mutually comparable using the specified comparator (that is, c.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the list). If the specified comparator is null then all elements in this list must implement the Comparable interface and the elements’s natural ordering should be used. This list must be modifiable, but need not be resizable.

可以看到,这个方法进行排序通过一个 Comparator 对象,如果传入参数为 null 的话,则会进行自然排序,但是注意:自然排序的前提是相应的实体类实现了 Comparable 接口,并重写了 compareTo() 方法。

总结

简单了解了一下 Comparable 和 Comparator 接口的作用和简单的使用方法,这里使用了一点 Lambda 表达式的知识,不过都只是很浅显的知识,应该不难理解(我也只是正在学习中,哈哈)。通过一个 Dog 类和 Cat 类进行讲解,我觉得很好,首先它很容易理解,并且可以快速掌握简单的使用方法(学习是渐进式的,要一直努力学习知识才行)。

到此这篇关于关于Java中Comparable 和 Comparator的用法的文章就介绍到这了,更多相关Comparable和Comparator的用法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文