Java中Comparable和Comparator的区别

来源:互联网 发布:在线画图软件 编辑:程序博客网 时间:2024/06/04 19:02

1. Comparable interface: 要比较或排序的类需要实现compareTo()方法,之后可以直接使用Collections.sort()和Arrays.sort()方法排序。

public class Car implements Comparable {    public int compareTo(Object arg0) {        Car car = (Car) arg0;        if (this.carId < car.carId) {            return -1;        } else if (this.carId > car.carId) {            return 1;        } else {            return 0;        }    }}
2. Comparator interface: 要比较或排序的类不需要实现compare()方法,用额外定义的一个比较类来实现。

public class CarSortByIdComparator implements Comparator<Car>{    public int compare(Car car1, Car car2) {        if (car1.carId() < car2.carId()) {            return -1;        } else if (car1.carId() > car2.carId()) {            return 1;        } else {            return 0;        }    }}
3. 对比

区别ComparableComparator实现位置必须是所需排序的类,所以只有一种方法在一个单独的类中,可以有多种方法实现接口类必须implements Comparable类不需要实现接口,一个单独的类implements Comparator<Object>实现方法int compareTo(Object o1)int compare(Object o1, Object o2)排序方法Collections.sort(List)Collections.sort(List, Comparator)PackageJava.lang.ComparableJava.util.Comparator4.Comparable代码示例:

  (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 0public 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(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());}}}
  (3)Output:

Before Sort  : Country Id: 1||Country name: IndiaCountry Id: 4||Country name: ChinaCountry Id: 3||Country name: NepalCountry Id: 2||Country name: BhutanAfter Sort  : Country Id: 1|| Country name: IndiaCountry Id: 2|| Country name: BhutanCountry Id: 3|| Country name: NepalCountry Id: 4|| Country name: China
5.Comparator代码示例:
  (1)Country.java

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 0 public class CountrySortByIdComparator implements Comparator<Country>{    @Override    public 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 countryName        Collections.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());}}}
  (4)Output

Before Sort by id : Country Id: 1||Country name: IndiaCountry Id: 4||Country name: ChinaCountry Id: 3||Country name: NepalCountry Id: 2||Country name: BhutanAfter Sort by id: Country Id: 1|| Country name: IndiaCountry Id: 2|| Country name: BhutanCountry Id: 3|| Country name: NepalCountry Id: 4|| Country name: ChinaAfter Sort by name: Country Id: 2|| Country name: BhutanCountry Id: 4|| Country name: ChinaCountry Id: 1|| Country name: IndiaCountry Id: 3|| Country name: Nepal
原文:http://www.java2blog.com/2013/02/difference-between-comparator-and.html


0 0
原创粉丝点击