【问题标题】:Comparator and Comparable比较器和可比
【发布时间】:2014-06-12 19:15:13
【问题描述】:

我浏览了有关比较器和可比性如何工作的教程,但我对以下内容感到困惑:ComparatorMain 类调用

  Collections.sort(listOfCountries,new Comparator<Country>() {

                    @Override
                    public int compare(Country o1, Country o2) {
                        return o1.getCountryName().compareTo(o2.getCountryName());
                    }
                });

但是 compareTo() 方法的逻辑似乎是按 countryId 进行比较,而不是 countryName:

    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(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;
    }

}

那么这怎么可能起作用呢?

这是整个 ComparatorMain 类:

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

                @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());
            }
    }

}

教程: http://www.javacodegeeks.com/2013/03/difference-between-comparator-and-comparable-in-java.html

【问题讨论】:

  • 我不明白你的问题。你能改写你的问题吗?
  • comparatorMain 类有一个 Collections.sort() 和一个具有 compare() 方法的匿名类。此 compare() 方法调用并返回来自 o1.getCountryName() 的 compareTo() 方法的结果,它只是一个字符串。 compareTo() 必须在一个类中实现,那么 String 如何使用它?唯一实现的 compareTo() 方法比较的是 countryID 而不是 countryName。我不明白什么?

标签: java interface compare comparator


【解决方案1】:

如果你使用

Collections.sort(countries);

然后这些国家将使用它们的自然顺序进行排序,即由它们的compareTo() 方法定义的顺序。因此,它们将按 ID 排序。如果集合包含 Comparable 对象的实例,则只能以这种方式对集合进行排序。

如果你使用

Collections.sort(countries, someComparator);

然后将使用作为参数传递的比较器 (someComparator) 定义的顺序对国家/地区进行排序。在您的情况下,由于比较器按名称比较国家/地区,因此它们将按名称排序。您可以通过这种方式对任何类型的对象进行排序。

因此,简而言之,传递比较器允许按照与类本身定义的顺序不同的顺序对事物进行排序。

【讨论】:

  • 但是 compare() 方法返回 o1.getCountryName().compareTo(o2.getCountryName());所以我们第一个对象 o1 的字符串 countryName 将调用它的 compareTo 方法,传递第二个对象 o2 的 countryName 进行比较。我不明白的是,当必须在类中实现 compareTo() 时,我们如何对字符串执行 compareTo()。其次,如果它以某种方式起作用,我们将传递对象,但 Country 类中的 compareTo() 方法会比较 countryID,而不是 countryName。
  • String 也实现了 Comparable,因此您可以在 String 上调用 compareTo,将其与另一个 String 进行比较。
  • 好的,所以它已经在String对象中实现了就是你说的?
  • 是的。字符串具有自然顺序,即字典顺序。所有其他基本类型(Integer、Long、Double、Date 等)也具有自然排序,因此您可以通过字段轻松比较复杂对象。见docs.oracle.com/javase/7/docs/api/java/lang/…
猜你喜欢
  • 2012-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-14
  • 1970-01-01
  • 2013-12-29
相关资源
最近更新 更多