简体   繁体   English

compareTo方法(在Comparable接口中)是否是递归的?

[英]Is the compareTo method (in the Comparable interface) recursive?

I am implementing the Comparable interface, and using it to compare the names of sports teams. 我正在实现Comparable接口,并使用它来比较运动队的名称。 I noticed that this was the simplest implementation of the compareTo method. 我注意到这是compareTo方法的最简单实现。 I was wondering why the method compareTo refers to itself in the body of the method. 我想知道为什么方法compareTo在方法主体中引用自身。 Isn't that some sort of never-ending recursion? 那不是某种永无止境的递归吗? How can you implement a method by defining it as itself? 如何通过将其定义为方法来实现方法?

public int compareTo(Team x)
{
    return teamName.compareTo(x.teamName);
}

You don't present the complete code that puzzles you, but presumably the method you do present belongs to a class Team of some package, and presumably that class's teamName field is of a type different from Team (I'll suppose it's java.lang.String ). 您不会提供让您感到困惑的完整代码,但是大概您提供的方法属于某个程序包的类Team ,并且大概该类的teamName字段与Team的类型不同(我假设它是java.lang.String )。 In that case, the method you present is not recursive at all. 在这种情况下,您提供的方法根本不是递归的。 Method some.package.Team.compareTo(some.package.Team) invokes method java.lang.String.compareTo(java.lang.String) , which is a completely separate method. some.package.Team.compareTo(some.package.Team)方法调用方法java.lang.String.compareTo(java.lang.String) ,这是一个完全独立的方法。

如果teamNameString类型,则调用String的compareTo(...)

teamName is probably a String . teamName可能是String So it uses String.compareTo() method. 因此,它使用String.compareTo()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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