【发布时间】: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