using compareTo method when overriding compareTo?

。_饼干妹妹 提交于 2019-12-25 09:24:29

问题


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:


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.



来源:https://stackoverflow.com/questions/39680973/using-compareto-method-when-overriding-compareto

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!