I have an assignment to make a Country class with two fields(name, capital) which at first has to be compared with another Country based on the name. Afterwards without changing anything I have to make another test which cares only about the capital regarding comparison. How to do two different comparison methods in the same class ? This is what I've done so far :
Country class :
public class Country implements Comparable {
private String name;
private String capital;
public Country(String name, String capital) {
this.name = name;
this.capital = capital;
}
public String getName() {
return name;
}
public String getCapital() {
return capital;
}
@Override
public String toString() {
return "Country{" +
"name='" + name + '\'' +
", capital='" + capital + '\'' +
'}';
}
public static final Comparator<Country> nameComparator = (country, secondCountry) -> country.getName().compareTo(secondCountry.getName());
public static final Comparator<Country> capitalComparator = (country, secondCountry) -> country.getCapital().compareTo(secondCountry.getCapital());
@Override
public int compareTo(Object o) {
return 0;
}
}
Method which checks if countries are sorted correctly:
public boolean isSorted(List<Country> countryList) {
boolean sorted = Ordering.natural().isOrdered(countryList);
return sorted;
}
And my test:
@org.junit.Test
public void testIfTheListIsSorted () {
CountryDAO countryDAO = new CountryDAO();
List<Country> countryList = countryDAO.getCountryList();
Collections.sort(countryList, Country.nameComparator);
assertTrue(countryDAO.isSorted(countryList));
}
What do I have to change in order to compare at my choice , whether by name or by capital ? And both ways being testable. Thanks in advance..
Aucun commentaire:
Enregistrer un commentaire