简体   繁体   中英

Using compareTo in Java to Sort

Basically i'm attempting to write a compareTo that does the comparison based on the value of compareByWord . If compareByWord is true, I want it to compare based on the word, but if it's false, I want it to compare based on 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;
}
}

My class was perfect before I tried to implement this, not sure where I'm going wrong here. Any and all help is much appreciated.

Change the declaration to

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

The method signature in Comparable<WordCount> is compareTo(WordCount obj) while for the raw version it's compareTo(Object obj) .

With the usage of @Override , the compiler makes sure that you actually override the parent method. And the problem is that compareTo(WordCount obj) does not override compareTo(Object obj) .

Use Integer count not int count . Integer is an object which implements Comparable whereas int is a primitive as the error message describes. For javadocs:

public final class Integer
extends Number
implements Comparable<Integer>

Make sure you change your accessor methods to use Integer as well of course.

That will take care of your final error.

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

So pass Object, not WordCount. Now you're trying to overload this function, not override .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM