Java中Comparator和Comparable之间的区别
常见的面试问题之一是“比较器和可比较器之间有什么区别”。 或“您将如何通过其ID或名称对员工对象集合进行排序”。为此,我们可以使用两个接口,即Comparator和Comparable。在我们真正看到差异之前,让我简要介绍一下两者。
可比接口:要对其进行排序的对象的类必须实现此接口。在此,我们必须实现compareTo(Object)方法。
例如:
public class Country implements Comparable{@Overridepublic int compareTo(Object arg0) {Country country=(Country) arg0;return (this.countryId < country.countryId ) ? -1: (this.countryId > country.countryId ) ? 1:0 ;
}}
如果任何类实现可比较的接口,则可以使用Collection.sort()或Arrays.sort()自动对该对象的集合进行排序。对象将基于该类中的compareTo方法进行排序。
在Java中实现Comparable的对象可以用作SortedMap(如TreeMap)或SortedSet(如TreeSet)中的键,而无需实现任何其他接口。
Comparator接口:需要对其进行排序的对象的类无需实现此接口。某些第三类可以实现此接口进行排序。egCountrySortByIdComparator类可以实现Comparator接口以按ID对国家对象的集合进行排序。 例如:
public class CountrySortByIdComparator implements Comparator<Country>{@Overridepublic int compare(Country country1, Country country2) {return (country1.getCountryId() < country2.getCountryId() ) ? -1: (country1.getCountryId() > country2.getCountryId() ) ? 1:0 ;}}
使用Comparator界面,我们可以根据要排序的对象的不同属性编写不同的排序。您可以使用匿名比较器在特定代码行进行比较。 例如:
Country indiaCountry=new Country(1, 'India');Country chinaCountry=new Country(4, 'China');Country nepalCountry=new Country(3, 'Nepal');Country bhutanCountry=new Country(2, 'Bhutan');List<Country> listOfCountries = new ArrayList<Country>();listOfCountries.add(indiaCountry);listOfCountries.add(chinaCountry);listOfCountries.add(nepalCountry);listOfCountries.add(bhutanCountry); //Sort by countryNameCollections.sort(listOfCountries,new Comparator<Country>() {@Overridepublic int compare(Country o1, Country o2) {return o1.getCountryName().compareTo(o2.getCountryName());}});
比较器vs可比
参数 | 可比 | 比较器 |
排序逻辑 | 排序逻辑必须在要对其对象进行排序的同一类中。 因此,这称为对象的自然排序 | 排序逻辑在单独的类中。 因此,我们可以根据要排序的对象的不同属性编写不同的排序。 例如,使用ID,名称等进行排序 |
实作 | 对其对象进行排序的类必须实现此接口。例如Country类需要实现与id对应的country对象的收集类似的实现 | 要排序对象的类不需要实现此接口。其他一些类也可以实现此接口。 Eg-CountrySortByIdComparator类可以实现Comparator接口,以按ID对国家/地区对象的集合进行排序 |
排序方式 |
int compareTo(Object o1) 该方法将该对象与o1对象进行比较并返回一个整数,其值具有以下含义 1.正数–该对象大于o1 2.零–此对象等于o1 3.负数–该对象小于o1 |
int compare(对象o1,对象o2) 此方法比较o1和o2对象。 并返回一个整数。其值具有以下含义。 1.正数– o1大于o2 2.零– o1等于o2 3.负数– o1小于o1 |
调用方式 |
Collections.sort(列表) 在这里,对象将根据CompareTo方法进行排序 |
Collections.sort(列表,比较器) 在这里,对象将根据Comparator中的Compare方法进行排序 |
包 | Java.lang.Comparable | Java.util.Comparator |
Java代码:
对于Comparable:我们将创建具有属性ID和名称的country类,该类将实现Comparable接口并实现CompareTo方法以按ID对国家对象的集合进行排序。
1. Country.java
package org.arpit.javapostsforlearning;
//If this.cuntryId < country.countryId:then compare method will return -1
//If this.countryId > country.countryId:then compare method will return 1
//If this.countryId==country.countryId:then compare method will return 0
public class Country implements Comparable{int countryId;String countryName;public Country(int countryId, String countryName) {super();this.countryId = countryId;this.countryName = countryName;}@Overridepublic int compareTo(Object arg0) {Country country=(Country) arg0;return (this.countryId < country.countryId ) ? -1: (this.countryId > country.countryId ) ? 1:0 ;}public int getCountryId() {return countryId;}public void setCountryId(int countryId) {this.countryId = countryId;}public String getCountryName() {return countryName;}public void setCountryName(String countryName) {this.countryName = countryName;}}
2.ComparatorMain.java
package org.arpit.javapostsforlearning;import java.util.ArrayList;
import java.util.Collections;
import java.util.List;public class ComparatorMain {/*** @author Arpit Mandliya*/public static void main(String[] args) {Country indiaCountry=new Country(1, 'India');Country chinaCountry=new Country(4, 'China');Country nepalCountry=new Country(3, 'Nepal');Country bhutanCountry=new Country(2, 'Bhutan');List<Country> listOfCountries = new ArrayList<Country>();listOfCountries.add(indiaCountry);listOfCountries.add(chinaCountry);listOfCountries.add(nepalCountry);listOfCountries.add(bhutanCountry);System.out.println('Before Sort : ');for (int i = 0; i < listOfCountries.size(); i++) {Country country=(Country) listOfCountries.get(i);System.out.println('Country Id: '+country.getCountryId()+'||'+'Country name: '+country.getCountryName());}Collections.sort(listOfCountries);System.out.println('After Sort : ');for (int i = 0; i < listOfCountries.size(); i++) {Country country=(Country) listOfCountries.get(i);System.out.println('Country Id: '+country.getCountryId()+'|| '+'Country name: '+country.getCountryName());}}}
输出:
Before Sort :
Country Id: 1||Country name: India
Country Id: 4||Country name: China
Country Id: 3||Country name: Nepal
Country Id: 2||Country name: Bhutan
After Sort :
Country Id: 1|| Country name: India
Country Id: 2|| Country name: Bhutan
Country Id: 3|| Country name: Nepal
Country Id: 4|| Country name: China
对于Comparator:我们将创建具有属性ID和名称的country类,并创建另一个CountryAortByIdComparator类,该类将实现Comparator接口并实现compare方法以按ID对国家对象的集合进行排序,并且还将看到如何使用匿名比较器。
1.国家/地区
package org.arpit.javapostsforlearning;public class Country{int countryId;String countryName;public Country(int countryId, String countryName) {super();this.countryId = countryId;this.countryName = countryName;}public int getCountryId() {return countryId;}public void setCountryId(int countryId) {this.countryId = countryId;}public String getCountryName() {return countryName;}public void setCountryName(String countryName) {this.countryName = countryName;}}
2.CountrySortbyIdComparator.java
package org.arpit.javapostsforlearning;import java.util.Comparator;
//If country1.getCountryId()<country2.getCountryId():then compare method will return -1
//If country1.getCountryId()>country2.getCountryId():then compare method will return 1
//If country1.getCountryId()==country2.getCountryId():then compare method will return 0public class CountrySortByIdComparator implements Comparator<Country>{@Overridepublic int compare(Country country1, Country country2) {return (country1.getCountryId() < country2.getCountryId() ) ? -1: (country1.getCountryId() > country2.getCountryId() ) ? 1:0 ;}}
3,ComparatorMain.java
package org.arpit.javapostsforlearning;import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;public class ComparatorMain {/*** @author Arpit Mandliya*/public static void main(String[] args) {Country indiaCountry=new Country(1, 'India');Country chinaCountry=new Country(4, 'China');Country nepalCountry=new Country(3, 'Nepal');Country bhutanCountry=new Country(2, 'Bhutan');List<Country> listOfCountries = new ArrayList<Country>();listOfCountries.add(indiaCountry);listOfCountries.add(chinaCountry);listOfCountries.add(nepalCountry);listOfCountries.add(bhutanCountry);System.out.println('Before Sort by id : ');for (int i = 0; i < listOfCountries.size(); i++) {Country country=(Country) listOfCountries.get(i);System.out.println('Country Id: '+country.getCountryId()+'||'+'Country name: '+country.getCountryName());}Collections.sort(listOfCountries,new CountrySortByIdComparator());System.out.println('After Sort by id: ');for (int i = 0; i < listOfCountries.size(); i++) {Country country=(Country) listOfCountries.get(i);System.out.println('Country Id: '+country.getCountryId()+'|| '+'Country name: '+country.getCountryName());}//Sort by countryNameCollections.sort(listOfCountries,new Comparator<Country>() {@Overridepublic int compare(Country o1, Country o2) {return o1.getCountryName().compareTo(o2.getCountryName());}});System.out.println('After Sort by name: ');for (int i = 0; i < listOfCountries.size(); i++) {Country country=(Country) listOfCountries.get(i);System.out.println('Country Id: '+country.getCountryId()+'|| '+'Country name: '+country.getCountryName());}}}
输出:
Before Sort by id :
Country Id: 1||Country name: India
Country Id: 4||Country name: China
Country Id: 3||Country name: Nepal
Country Id: 2||Country name: Bhutan
After Sort by id:
Country Id: 1|| Country name: India
Country Id: 2|| Country name: Bhutan
Country Id: 3|| Country name: Nepal
Country Id: 4|| Country name: China
After Sort by name:
Country Id: 2|| Country name: Bhutan
Country Id: 4|| Country name: China
Country Id: 1|| Country name: India
Country Id: 3|| Country name: Nepal
参考: JCG合作伙伴 Arpit Mandliya在Java框架和面向初学者博客的设计模式中的 比较器与Java中的Comparable之间的区别 。
翻译自: https://www.javacodegeeks.com/2013/03/difference-between-comparator-and-comparable-in-java.html
Java中Comparator和Comparable之间的区别相关推荐
- Java中浅拷贝与深拷贝之间的区别
在深入探讨Java中浅表副本与深表副本之间的差异之前,让我们看看首先进行克隆的是什么. 什么是克隆? 克隆是在内存中创建现有对象的精确副本的过程.在Java中,java.lang.Object类的cl ...
- Java中抽象类和接口之间的区别
一些受欢迎的访谈问题是"抽象类和接口之间有什么区别","什么时候使用抽象类以及什么时候使用接口". 因此,在本文中,我们将讨论这个主题. 在探讨它们之间的差异之 ...
- Java中float与double之间的区别?
文章目录 float类型与double类型的区别 测试用例 Ending~! 提示:以下是本篇文章正文内容,下面案例可供参考 float类型与double类型的区别 float表示单精度浮点型,占用4 ...
- Java中Array和ArrayList之间的9个区别
array和ArrayList都是Java中两个重要的数据结构,在Java程序中经常使用. 即使ArrayList在内部由数组支持,了解Java中的数组和ArrayList之间的差异对于成为一名优秀的 ...
- java的Comparator和Comparable
java的Comparator和Comparable 当需要排序的集合或数组不是单纯的数字型时,通常可以使用Comparator或Comparable,以简单的方式实现对象排序或自定义排序. ...
- java == hashcode,java中==和equals和hashCode的区别
java中==和equals和hashCode的区别 == 的作用: 基本类型:比较的就是值是否相同 引用类型:比较的就是地址值是否相同(确切的说,是堆内存地址) equals 的作用: 引用类型:默 ...
- Java中实现接口与继承的区别
** Java中实现接口与继承的区别 ** 首先,先来了解一下什么是接口和继承.接口一般是使用interface来定义的.接口定义同类的定义类似,分为接口的声明和接口体,其中接口体由常量定义和方法定义 ...
- Java中long和Long有什么区别
Java中long和Long有什么区别(转) Java的数据类型分两种: 1.基本类型:long,int,byte,float,double,char 2. 对象类型(类): Long,Integer ...
- java的 x跟x_关于语法:java中的x ++和++ x有区别吗?
java中的++ x和x ++有区别吗? 提示大量相同的答案...... ...并提出第一个完全相同的答案... 最快的去战利品,按最旧排序,点击upvote.ohowoho. 我确信我有它! 无论如 ...
最新文章
- js怎么定义combobox_好程序员web前端教程分享新手应该怎么学习webpack
- 有医学又有计算机系的学校,中山最好的中专学校有哪些 十大中专学校排名
- Java反射实现几种方式
- 并归排序(看别人的看不懂,自己写了一个),排序思想是一样的
- 百度商业大规模微服务分布式监控系统-凤睛
- shell 中的 set命令 -e -o 选项作用
- matplotlib - 极坐标上的散点图
- Jquery 每天记一点2009-7-2
- 优先队列实现迪杰特斯拉模板
- 类进阶学习目标 java 1614957028
- kafka 主动消费_Kafka消费组(consumer group)
- iOS提交TestFlight测试显示缺少合规证明
- K3打印单据,提示:等待C盘释放空间,内存不足
- 如何获取git diff文件,并将其应用于作为同一存储库副本的本地分支?
- linux下文件和目录的颜色表示
- 计算机专业论文提纲,计算机硕士毕业论文提纲(范文精选)
- 360极速浏览器屏蔽百度广告
- c#直接横向打印LocalReport
- 买了一台云服务器能干嘛
- [CISCN2019 总决赛 Day2 Web1]Easyweb 1
热门文章
- matlab盒子分形维数_分形:盒子维数
- Quartz定时任务的基本搭建
- assertj断言异常_编写自定义的AssertJ断言
- 因此,Oracle杀死了java.net
- java 性能 优化_Java十大简单性能优化
- 跟踪反应流–将Spring Cloud Sleuth与Boot 2结合使用
- 使用Spring Boot构建REST Web服务
- Neo4j:Cypher – Neo.ClientError.Statement.TypeError:不知道如何添加Double和String
- maven 父maven_Maven的春天
- 使用TestContainers提高测试性能