在覆盖compareTo时使用compareTo方法

在覆盖compareTo时使用compareTo方法

本文介绍了在覆盖compareTo时使用compareTo方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当实现Comparable接口并覆盖compareTo方法时,

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;
    }
}

第三行,我意识到我可以在覆盖它时使用compareTo,并且它会自动按照自然顺序比较事物.但是在可比较的接口中,compareTo不是抽象方法.如果不定义它,它仍然可以比较吗?另外,为什么我不需要使用超级关键字来区分这个compareTo.

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.

推荐答案

您正在实现class Name extends Comparable<Name>中的方法compareTo.此类有一个名为name的成员.如果您在第三行中调用Name.compareTo,则会因无穷递归而崩溃,也无法调用Comparable.compareTo,这确实是抽象的.

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.

您正在调用X.compareTo,其中X是您用来声明成员变量name的类型.

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

换句话说,这仅在name不是instanceof Name的情况下有效.

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

顺便说一句,您将需要在最后一个if块中添加一个带有return语句的else分支,否则此代码段将无法编译.

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.

这篇关于在覆盖compareTo时使用compareTo方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 10:05