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中文网其他相关文章!

JavaachievesPlatFormIndependencethroughTheJavavIrtualMachine(JVM),允许Codetorunondifferentoperatingsystemsswithoutmodification.thejvmcompilesjavacodeintoplatform-interploplatform-interpectentbybyteentbytybyteentbybytecode,whatittheninternterninterpretsandectectececutesoneonthepecificos,atrafficteyos,Afferctinginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginging

JavaispoperfulduetoitsplatFormitiondence,对象与偏见,RichstandardLibrary,PerformanceCapabilities和StrongsecurityFeatures.1)Platform-dimplighandependectionceallowsenceallowsenceallowsenceallowsencationSapplicationStornanyDevicesupportingJava.2)

Java的顶级功能包括:1)面向对象编程,支持多态性,提升代码的灵活性和可维护性;2)异常处理机制,通过try-catch-finally块提高代码的鲁棒性;3)垃圾回收,简化内存管理;4)泛型,增强类型安全性;5)ambda表达式和函数式编程,使代码更简洁和表达性强;6)丰富的标准库,提供优化过的数据结构和算法。

javaisnotirelyPlatemententduetojvmvariationsandnativecodinteintration,butitlargelyupholdsitsitsworapromise.1)javacompilestobytecoderunbythejvm

thejavavirtualmachine(JVM)IsanabtractComputingmachinecrucialforjavaexecutionasitrunsjavabytecode,使“ writeononce,runanywhere”能力

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

Java的五大特色是多态性、Lambda表达式、StreamsAPI、泛型和异常处理。1.多态性让不同类的对象可以作为共同基类的对象使用。2.Lambda表达式使代码更简洁,特别适合处理集合和流。3.StreamsAPI高效处理大数据集,支持声明式操作。4.泛型提供类型安全和重用性,编译时捕获类型错误。5.异常处理帮助优雅处理错误,编写可靠软件。


热AI工具

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

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

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

WebStorm Mac版
好用的JavaScript开发工具

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境