【发布时间】: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