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); } }
运行截图:
补充说明: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() 方法。
以上是Java中Comparable和Comparator怎么使用的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

热门话题

Java 8引入了Stream API,提供了一种强大且表达力丰富的处理数据集合的方式。然而,使用Stream时,一个常见问题是:如何从forEach操作中中断或返回? 传统循环允许提前中断或返回,但Stream的forEach方法并不直接支持这种方式。本文将解释原因,并探讨在Stream处理系统中实现提前终止的替代方法。 延伸阅读: Java Stream API改进 理解Stream forEach forEach方法是一个终端操作,它对Stream中的每个元素执行一个操作。它的设计意图是处

胶囊是一种三维几何图形,由一个圆柱体和两端各一个半球体组成。胶囊的体积可以通过将圆柱体的体积和两端半球体的体积相加来计算。本教程将讨论如何使用不同的方法在Java中计算给定胶囊的体积。 胶囊体积公式 胶囊体积的公式如下: 胶囊体积 = 圆柱体体积 两个半球体体积 其中, r: 半球体的半径。 h: 圆柱体的高度(不包括半球体)。 例子 1 输入 半径 = 5 单位 高度 = 10 单位 输出 体积 = 1570.8 立方单位 解释 使用公式计算体积: 体积 = π × r2 × h (4
