第四章 java中Comparator和Comparable的区别


常见的面试问题之一是“Comparator 和 Comparable 之间有什么区别”。或者“你将如何按 id 或 name 对员工对象的集合进行排序”。为此,我们可以使用两个接口,即 Comparator 和 Comparable。在我们真正看到差异之前,让我先简单介绍一下两者。

可比接口:

待排序对象的类必须实现该接口。在此,我们必须实现 compareTo(Object) 方法。 例如:

public class Country implements Comparable{
       @Override
    public int compareTo(Country country) {
        return (this.countryId < country.countryId ) ? -1: (this.countryId > country.countryId ) ? 1:0 ;
}}

如果任何类实现了可比较的接口,则可以使用 Collection.sort() 或 Arrays.sort() 自动对该对象的集合进行排序。Object 将根据该类中的 compareTo 方法进行排序。 在 java 中实现 Comparable 的对象可以用作 TreeMap 等 SortedMap 或 TreeSet 等 SortedSet 中的键,而无需实现任何其他接口。

比较器接口:

需要排序的对象的类不需要实现这个接口。有些第三类可以实现这个接口来进行排序。egCountrySortByIdComparator 类可以实现Comparator 接口来对国家对象的集合按id 进行排序。例如:

public class CountrySortByIdComparator implements Comparator{

    @Override
    public 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 russiaCountry=new Country(4, "Russia");
         Country englandCountry=new Country(3, "England");
         Country germanyCountry=new Country(2, "Germany");


         List listOfCountries = new ArrayList();
         listOfCountries.add(indiaCountry);
         listOfCountries.add(russiaCountry);
         listOfCountries.add(englandCountry);
         listOfCountries.add(germanyCountry); 

 //Sort by countryName

            Collections.sort(listOfCountries,new Comparator() {

                @Override
                public int compare(Country o1, Country o2) {

                    return o1.getCountryName().compareTo(o2.getCountryName());
                }
            });
范围 可比 比较器
排序逻辑 排序逻辑必须在其对象被排序的同一类中。因此这被称为对象的自然排序 排序逻辑在单独的类中。因此,我们可以根据待排序对象的不同属性编写不同的排序。例如,使用 id、name 等进行排序。
执行 要排序的对象的类必须实现这个接口。例如 Country 类需要实现类似于按 id 收集国家对象的类 待排序对象的类不需要实现该接口。其他类可以实现该接口。eg-CountrySortByIdComparator 类可以实现 Comparator 接口,通过 id 对 country 对象的集合进行排序
排序方式 int compareTo(Object o1) 此方法将此对象与 o1 对象进行比较,并返回一个整数。其值具有以下含义 1.正--此对象大于 o1 2.零--此对象等于 o1 3.负--此对象是小于 o1 int compare(Object o1,Object o2) 此方法比较 o1 和 o2 对象。并返回一个整数。其值具有以下含义。 1. 正 - o1 大于 o2 2. 零 - o1 等于 o2 3. 负 - o1 小于 o1
调用方法 Collections.sort(List) 这里的对象将根据 CompareTo 方法进行排序 Collections.sort(List, Comparator) 这里的对象将根据 Comparator 中的 Compare 方法进行排序
包裹 Java.lang.Comparable Java.util.Comparator

Java代码:

对于可比:

我们将创建具有属性 id 和 name 的类 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;
    }

    @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.javapostsforlearning;

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 indiaCountry=new Country(1, "India");
        Country russiaCountry=new Country(4, "Russia");
        Country englandCountry=new Country(3, "England");
        Country germanyCountry=new Country(2, "Germany");

        List listOfCountries = new ArrayList();
        listOfCountries.add(indiaCountry);
        listOfCountries.add(russiaCountry);
        listOfCountries.add(englandCountry);
        listOfCountries.add(germanyCountry);

        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: Russia
Country Id: 3||Country name: England
Country Id: 2||Country name: Germany
After Sort  : 
Country Id: 1|| Country name: India
Country Id: 2|| Country name: Germany
Country Id: 3|| Country name: England
Country Id: 4|| Country name: Russia

对于比较器:

我们将创建具有属性 id 和 name 的类 country 并将创建另一个类 CountrySortByIdComparator ,它将实现 Comparator 接口并实现 compare 方法来按 id 对国家对象的集合进行排序,我们还将了解如何使用匿名比较器。

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{

    @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 russiaCountry=new Country(4, "Russia");
        Country englandCountry=new Country(3, "England");
        Country germanyCountry=new Country(2, "Germany");

        List listOfCountries = new ArrayList();
        listOfCountries.add(indiaCountry);
        listOfCountries.add(russiaCountry);
        listOfCountries.add(englandCountry);
        listOfCountries.add(germanyCountry);

        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() {

            @Override
            public 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: Russia
Country Id: 3||Country name: England
Country Id: 2||Country name: Germany
After Sort by id: 
Country Id: 1|| Country name: India
Country Id: 2|| Country name: Germany
Country Id: 3|| Country name: England
Country Id: 4|| Country name: Russia
After Sort by name: 
Country Id: 2|| Country name: England
Country Id: 4|| Country name: Germany
Country Id: 1|| Country name: India
Country Id: 3|| Country name: Russia


原文链接:https://codingdict.com/