Problems with overriding compareTo() in interface Comparable

Smpl Fcts :

I'm working on a programm that has to override the CompareTo() in Comparable to make Collections.sort() work. For I am working with an ArrayList made up of Assistants, that I have to sort depending on the name.

I've looked around the forum and found that and tried changing

public class Assistant{

to

public class Assistant implements Comparable<Assistant>{

which in return allows me to use the Collections.sort() in another class and doesn't warn me about any errors, however, two new errors appear.

To start with, in this same line

public class Assistant implements Comparable<Assistant>{

it tells me that "it is not abstract and does not override compareTo(Assistant) in Comparable." And when I go to the compareTo() I've created:


    @Override
    public int compareTo(Object o2){
        Assistant m2 = (Assistant) o2;

        if(this.name.compareTo(m2.name) == 0){
            return 0;
        }else if(this.name.compareTo(m2.name)<0){
            return -1;
        }else{
            return 1;
        }
    }


(The Assistant's constructor only has name in it).

However, in this place I have an error in @Override : "method does not override or implement a method from a supertype".

And in the next line

    public int compareTo(Object o2){

I get another error (which is related to the last) telling me: "Name clash: compareTo(Object) in Assistant and compareTo(Assistant) in Assistant have the same erasure, yet neither overrides the other."

I sort of understand the problem, I am not overriding the original compareTo().

I'm a newbie at java, therefore if anyone finds the problem I would be grateful if you could also explain what I am doing wrong (or missing).

Thank you :)

Andronicus :

It's because you have parametrized Comparable (type parameter is Assistant). This should do it (I have simplified it a bit):

@Override
public int compareTo(Assistant o){
    return this.name.compareTo(o.name);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=85232&siteId=1