using compareTo method when overriding compareTo?

2019-09-10 22:10发布

when implements Comparable interface and override compareTo method,

@Override
public int compareTo(Name o) {
    int val = this.name.compareTo(o.name);
    if (val != 0) {
        return val;
    }        
    if (count != o.count) {
        return count - o.count;
    }
}

The third line, I realized that I can use compareTo when I override it, and it automatically compares things follows the natural order. But isn't compareTo an abstract method in the comparable interface. Without defining it, it still does compare? Also, why I do not need to use super keyword to distinguish this compareTo.

1条回答
干净又极端
2楼-- · 2019-09-10 22:38

You are implementing the method compareTo in the class Name extends Comparable<Name>. This class has a member called name.If you were calling Name.compareTo in the third line, you would get a crash from infinity recursion, nor can you call Comparable.compareTo, which is abstract indeed.

You are calling X.compareTo, where X is the type you declared the member variable name with.

In other words, this will only work if name is not instanceof Name.

By the way, you will need to add an else branch with a return statement to your last if block, or this snippet won't compile.

查看更多
登录 后发表回答