//This code is written in java and please follow directions as given and impleme
ID: 3830460 • Letter: #
Question
//This code is written in java and please follow directions as given and implement code whete it is asked.
The class City has two instance variables that store the name and population of a city. This class implements the Comparable interface that allows two objects of the City class to be compared based on their population
You have been provided with a partially implemented City class along with a test class.
Implement the abstract method compareTo from the Comparable<T> interface and test the code using the given test class.
public class CityCompare {
public static void main(String[] args) {
City city1, city2;
city1 = new City("Atlanta", 450000);
city2 = new City("Boston", 650000);
if ((city1.compareTo(city2)) > 0)
System.out.println("Atlanta has a greater population than Boston ");
else
System.out.println("Boston has a greater population than Atlanta");
} //main
}// CityCompare
class City implements Comparable<City>{
String name;
double population;
public City(String name, double population){
this.name = name;
this.population = population;
}
public double getPopulation()
{ return population;}
public void setPopulation(double population)
{ this.population = population;}
public String getName()
{return name;}
/****************** implement the compareTo Interface here *****************/
} // City
Explanation / Answer
public class CityCompare {
public static void main(String[] args) {
City city1, city2;
city1 = new City("Atlanta", 450000);
city2 = new City("Boston", 650000);
if ((city1.compareTo(city2)) > 0)
System.out.println("Atlanta has a greater population than Boston ");
else
System.out.println("Boston has a greater population than Atlanta");
} // main
}// CityCompare
public class City implements Comparable<City> {
String name;
double population;
public City(String name, double population) {
this.name = name;
this.population = population;
}
public double getPopulation() {
return population;
}
public void setPopulation(double population) {
this.population = population;
}
public String getName() {
return name;
}
/****************** implement the compareTo Interface here *****************/
@Override
public int compareTo(City o) {
return this.getName().compareTo(o.getName()); // sorting based on city name
}
} // City
OUTPUT:
Boston has a greater population than Atlanta
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.