【问题标题】:How to use Comparator? [duplicate]如何使用比较器? [复制]
【发布时间】:2019-07-15 18:51:15
【问题描述】:

我正在尝试编写一些代码,我需要使用比较器,但我不知道比较器是什么。您能否解释一下我们为什么使用比较器以及什么是可比较的?

而且我这样做是否正确?我尝试在顶部使用 implements Comparator,但它不起作用。

这是我的代码。

 import java.util.Comparator;
 public class MedalCount {
 String name;
 int goldMedals;
 int silverMedals;
 int bronzeMedals;
 int totalMedals;


/** 
 * Creates a new MedalCount instance.
 * @param name is the name of the nation
 * @param nGoldMedals is the number of gold medals
 * @param nSilverMedals is the number of silver medals
 * @param nBronzeMedals is the number of bronze medals
 */
public MedalCount(String name, int nGoldMedals, int nSilverMedals,
                  int nBronzeMedals) {
    this.name = name;
    this.goldMedals = nGoldMedals;
    this.silverMedals = nSilverMedals;
    this.bronzeMedals = nBronzeMedals;
    totalMedals = nGoldMedals + nSilverMedals + nBronzeMedals;
}

/** Return a string describing the medal count information for the country */
public String toString() {
    return name + ":\t" + goldMedals + ",\t" + silverMedals + ",\t" 
        + bronzeMedals + ",\t"+ totalMedals;
}

/** 
 * Compare instance of medal count with another. 
 * Nations compared based on number of total medals (descending order).
 */
// TODO: create comparator
public static final Comparator<MedalCount> COMPARATOR = new Comparator<MedalCount>() {
    @Override
    public int compare(MedalCount totalMedals1, MedalCount TotalMedals2) {
        if (totalMedals1.totalMedals >= totalMedals1.totalMedals) {
            return 1;
        } else
            return 0;


    }
}




/** Comparator for sorting by nation name alphabetically */
// TODO: create comparator


/** Comparator for sorting by gold medal count (descending order) */
// TODO: create comparator 

}

【问题讨论】:

    标签: java algorithm comparator


    【解决方案1】:

    它用于进行相等检查。假设您有一个属于同一类的对象列表。如果所有 3 位数据都相同,则该类具有 3 个属性,您可以说它们是相等的。但是您也可以说第二个属性比第三个属性更高,而第一个属性排在最后。因此,在比较所述对象的列表时,像 、>、 之类的运算符的行为方式就是如此。因此,您可以执行诸如对该类的对象列表进行排序等操作。

    其他背景可从the Comparator javadoc获得。

    【讨论】:

      【解决方案2】:

      比较方法中您的条件错误,两个对象都相同。将 totalMedals1 更改为 totalMedals2

      当您对这些接口使用的对象进行排序时,例如您希望根据此逻辑使用 Collections.sort(ListOfMedal) 您的对象将得到排序

      Comparable 提供单个排序序列,Comparator 提供多个排序序列,请尝试以下代码

      if (totalMedals1.totalMedals >= totalMedals2.totalMedals) return 1;
      if (totalMedals1.totalMedals <= totalMedals2.totalMedals) return -1;
      else return 0;
      

      【讨论】:

        【解决方案3】:

        您的代码中的错误在这一行:if (totalMedals1.totalMedals &gt;= totalMedals1.totalMedals)

        你需要比较两个对象,你有两次totalMedals1,从不使用totalMedals2

        【讨论】:

          猜你喜欢
          • 2020-04-10
          • 2019-03-19
          • 2017-04-09
          • 2014-04-14
          • 1970-01-01
          • 2018-03-23
          • 1970-01-01
          • 2022-11-10
          相关资源
          最近更新 更多