compareTo方法需要一些工作

Dus*_*tin 3 java

我需要按照城市的字母顺序将城市和州分类为一个arraylist,但如果两个城市的名字相同,那么州将成为决胜局.

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";
   }
} 
Run Code Online (Sandbox Code Playgroud)

这是代码的一部分我认为我应该为决胜局做条件,但我不知道如何编码.

public int compareTo(Object otherCity) {
   City other = (City) otherCity;
   if (name.equals(other.name)){

     return name.compareTo(other.name);  
   }
}
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激!谢谢!

Ell*_*sch 5

可比较是通用的,所以我建议你通过实现提供你的类型 Comparable<City>

class City implements Comparable<City>
Run Code Online (Sandbox Code Playgroud)

然后你可以用类似的东西来实现你的比较

@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);
}
Run Code Online (Sandbox Code Playgroud)

或使用三元组

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);
}
Run Code Online (Sandbox Code Playgroud)

此外,由于你的字段没有setter我建议你将它们标记为final,因此它们是不可变的

final String name;
final String state;
Run Code Online (Sandbox Code Playgroud)