I'm trying to write some code and I need to use a comparator, but I have no idea what a comparator is. Could you please explain why we use Comparators and what is comparable?
And also am I doing this correctly? I tried to use implements Comparator<> on the top, but it was not working.
Here is my code.
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
}