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之间的区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 新萝卜u盘启动制作工具怎样按装系统(用新
- 下一篇: Microsoftoffice2010激