The compareTo method needs some work
I need to sort the cities and states in the arraylist in alphabetical order of cities, but if 2 cities have the same name, the state will be a tiebreaker.
public class City implements Comparable
{
String name;
String state;
/**
** A constructor for the city and state.
** @param name the name of the city.
** @param state the name of the state.
*/
public City(String name, String state)
{
this.name = name;
this.state = state;
}
//Gets the name and returns it.
public String getName()
{
return name;
}
//Gets the state and returns it.
public String getState()
{
return state;
}
public int compareTo(Object otherCity)
{
City other = (City) otherCity;
if (name.equals(other.name))
{
return name.compareTo(other.name);
}
public String toString()
{
return getClass().getName() + "[Name: " + name
+ ", State: " + state + "]\n";
}
}
This is the piece of code that I believe in where I should make the condition for the tiebreak, but I'm not sure how to code it.
public int compareTo(Object otherCity) {
City other = (City) otherCity;
if (name.equals(other.name)){
return name.compareTo(other.name);
}
}
Any help would be greatly appreciated! Thank!
Comparable generic, so I suggest you provide your type by doing Comparable<City>
class City implements Comparable<City>
Then you can implement your comparisons with something like
@Override
public int compareTo(City other) {
int r = this.name.compareTo(other.name);
if (r != 0) {
return r;
} // the names are not the same, compare the states
return this.state.compareTo(other.state);
}
or using triple
public int compareTo(City other) {
int r = this.name.compareTo(other.name);
// if (r != 0) then the names are not the same, compare the states
return (r != 0) ? r : this.state.compareTo(other.state);
}
Also, since your fields have no setters, I suggest you mark them as final to be immutable
final String name;
final String state;
(I'm going to assume that you agreed with my suggestion in the comments and linked to the type Comparable
.)
If the city name is equivalent, then the state is a tiebreaker. It's simple:
public int compareTo(@Nullable City otherCity) {
if(null == otherCity) {
return 1;
}
if(name.compareTo(otherCity.getName() == 0) {
return state.compareTo(otherCity.getState());
} else {
return name.compareTo(otherCity.getName());
}
}
There's an optimization out there where you don't have to make two calls getName
, but that should give you a general idea. Also, you have setters / getters; your fields should be private
.
You can try this. Here I am considering the meaning of a state if two cities are equal.
public int compareTo(Object otherCity){
City other = (City) otherCity;
int iReturn = name.compareTo(other.name);
if (iReturn == 0){
//use your logic what to do when strings are equal. e.g.
iReturn = iReturn = state.compareTo(other.state);
}
return iReturn;
}