Reputation: 257
I'm trying to use compareTo method to compare String first by String length then if 2 length are equal, String are further sorted in lexicographic order. Here's my code so far, it does sort in length first however fail to further sort in lexicographic order when String length are equal.
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;
}
Upvotes: 0
Views: 164
Reputation:
You forgot to specify return
statement
change
else{ this.word.compareTo(testStr2.word);
to
else{ return this.word.compareTo(testStr2.word);
Upvotes: 4