compareTo方法需要一些工作

时间:2014-09-26 02:50:18

标签: 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";
   }
} 

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

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

     return name.compareTo(other.name);  
   }
}

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

3 个答案:

答案 0 :(得分:5)

可比较是通用的,因此我建议您通过实施Comparable<City>

来提供您的类型
class City implements Comparable<City>

然后你可以用

之类的东西来实现你的比较
@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);
}

或使用ternary

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);
}

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

final String name;
final String state;

答案 1 :(得分:2)

(我假设你在评论中提出了我的建议,并对你的Comparable进行打字。)

如果城市名称相同,那么州就是决胜局。这很简单:

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());
    }
}

那里有一个优化,你不必对getName进行两次调用,但这应该给你一般的想法。此外,你有setter / getters;您的字段应为private

答案 2 :(得分:2)

你可以试试这个。在这里,我考虑两个城市相等的州值。

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;  
}