温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java中Comparable和Comparator怎么使用

发布时间:2023-04-08 16:39:22 来源:亿速云 阅读:138 作者:iii 栏目:开发技术

这篇文章主要讲解了“Java中Comparable和Comparator怎么使用”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Java中Comparable和Comparator怎么使用”吧!

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);
	}
}

运行截图:

Java中Comparable和Comparator怎么使用

补充说明: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&rsquo;s natural ordering should be used. This list must be modifiable, but need not be resizable.

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

感谢各位的阅读,以上就是“Java中Comparable和Comparator怎么使用”的内容了,经过本文的学习后,相信大家对Java中Comparable和Comparator怎么使用这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI