使用Java中的compareTo进行排序

时间:2014-04-16 19:03:49

标签: java class if-statement boolean compareto

基本上我试图编写一个compareTo,它根据compareByWord的值进行比较。如果compareByWord为真,我希望它根据单词进行比较,但如果它是假的,我希望它基于count进行比较。

class WordCount implements Comparable //Error saying WordCount must implement the inherited abstract method Comparable.compareto (Object)
{
String word;
int count;
static boolean compareByWord;
public WordCount(String aWord)
{
    setWord(aWord);
    count = 1;
}
private void setWord(String theWord)
{
    word=theWord;
}
public void increment()
{
    count+=1;
}
public static void sortByWord()
{
    compareByWord = true;
}
public static void sortByCount()
{
    compareByWord = false;
}
public String toString()
{
    String result = String.format("%s (%d)",word, count);
    return result;
}
public String getWord()
{
    return word;
}
public int getCount()
{
    return count;
}
@Override
public int compareTo(WordCount other) {  //Error saying compareTo (WordCount) of type WordCount must override or implement a supertype method.
    if (compareByWord == true)
    {
        return word.compareTo(other.getWord());
    }
    if (compareByWord == false)
    {
        return count.compareTo(other.getCount()); //Error saying it cannot invoke compareTo int on primitive type int.
    }
    return 0;
}
}

在我尝试实现这个目标之前,我的课程很完美,不知道我在哪里出错了。非常感谢任何和所有帮助。

3 个答案:

答案 0 :(得分:0)

将声明更改为

class WordCount implements Comparable<WordCount> { // generic version

Comparable<WordCount>中的方法签名为compareTo(WordCount obj),而原始版本为compareTo(Object obj)

使用@Override时,编译器会确保您实际覆盖父方法。问题是compareTo(WordCount obj)没有覆盖compareTo(Object obj)

答案 1 :(得分:0)

使用Integer count而不是int count。 Integer是实现Comparable的对象,而int是错误消息描述的基元。对于javadocs:

public final class Integer
extends Number
implements Comparable<Integer>

当然,请确保将访问者方法更改为使用Integer。

这会照顾到你的最终错误。

答案 2 :(得分:0)

must implement the inherited abstract method Comparable.compareto (Object)

所以传递Object,而不是WordCount。现在您正在尝试重载此功能,而不是覆盖