在java中Comparable接口
时间:2020-02-23 14:34:45 来源:igfitidea点击:
在本教程中,我们将看到如何在Java中使用Comparable给对象列表排序。
Comparable接口:
类要排序的对象必须实现此接口。
在此,我们必须实现Compareto(对象)方法。
例如:
public class Country implements Comparable{ @Override public int compareTo(Country country) { return (this.countryId < country.countryId ) ? -1: (this.countryId > country.countryId ) ? 1:0 ; }}
如果任何类实现可比的Inteface,则可以使用Collection.sort()或者arrays.sort()自动对该对象进行排序。
对象将根据该类中的CompareTo方法进行排序。
在Java中实现的对象可以用作SortedMap中的键,如TreeMAP或者SortedSet,如TreeSet,而不实现任何其他接口。
排序逻辑必须在同一类中,其对象正在排序。
因此,这被称为对象的自然排序
Java代码:
Comparable
我们将创建具有属性ID和name的类国家。
此类将实现可比接口并实现Compareto方法以按ID对国家对象进行排序。
1.Country.java.
package org.arpit.theitroad; //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; } @Override public int compareTo(Country country) { 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.comparablemain.java.
package org.arpit.theitroad; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ComparableMain { /** * @author Arpit Mandliya */ public static void main(String[] args) { Country San FrancecoCountry=new Country(1, "San Franceco"); Country chinaCountry=new Country(4, "China"); Country nepalCountry=new Country(3, "Nepal"); Country bhutanCountry=new Country(2, "Bhutan"); List listOfCountries = new ArrayList(); listOfCountries.add(San FrancecoCountry); 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: San Franceco 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: San Franceco Country Id: 2|| Country name: Bhutan Country Id: 3|| Country name: Nepal Country Id: 4|| Country name: China