【问题标题】:String comparison use compareTo字符串比较使用 compareTo
【发布时间】:2015-05-16 16:12:50
【问题描述】:

我正在尝试使用 compareTo 方法首先通过字符串长度比较字符串,然后如果 2 长度相等,则字符串按字典顺序进一步排序。 到目前为止,这是我的代码,它首先按长度排序,但是当字符串长度相等时,它无法按字典顺序进一步排序。

public class TestString implements Comparable<TestString>
{
  String word;

  public TestString(String string) {
    word = string;
  }

  public String toString() {
    return word;
  }

  public int compareTo(TestString testStr2) {

      int length1=this.word.length();
      int length2=testStr2.word.length();

      if (length1 > length2) return 1;
      else if (length1 < length2) return -1;
      else{ this.word.compareTo(testStr2.word);
      }
    return 0;
  }

【问题讨论】:

    标签: java comparable compareto


    【解决方案1】:

    您忘记指定return 声明

    改变

    else{ this.word.compareTo(testStr2.word);
    

    else{ return this.word.compareTo(testStr2.word);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-05
      • 1970-01-01
      相关资源
      最近更新 更多