我正在做这个项目,我会得到一些书籍,我应该按照以下逻辑对其进行排序:
- 如果一本书的页数多于另一本书,则页数较多的书先显示。
- 如果两本书的页数相同,则按标题字母顺序排序。
- 如果两本书的页数和标题相同,则按作者字母顺序排序。
我尝试解决但没有成功,所以我查找了解决方案:
public class Book implements Comparable<Book>{
public int compareTo(Book specifiedBook) {
// First check if they have different page counts
if(this.numberOfPages != specifiedBook.numberOfPages){
// this will return a negative value if this < specified but will return a positive value if this > specified
return this.numberOfPages - specifiedBook.numberOfPages;
}
// If page counts are identical then check if the titles are different
if(!this.title.equals(specifiedBook.title){
return this.title.compareTo(specifiedBook.title);
}
// If page titles are also identical then return the comparison of the authors
return this.author.compareTo(specifiedBook.author);
}
}
我在这里不明白的是这部分“return this.title.compareTo(specifiedBook.title);”。我们如何在方法compareTo中使用方法compareTo,这不是递归吗?我知道,当我们实现comperable接口(interface)时,我们必须重写方法compareTo,但是我们如何在OverridencompareTo方法中使用该compareTo方法呢?在这种情况下以及一般情况下,它应该做什么?
令我困惑的是,我们如何使用刚刚在接口(interface)中声明的方法,它不是从父类继承的。它只是在类似的接口(interface)中声明,因此当我们实现该接口(interface)时,我们必须重写它
最佳答案
假设 title
和 author
是字符串,您将从 内部调用
。这不是递归。这是不同类中的方法。String.compareTo
(已实现) >Book.compareTo
关于java - 我不明白我们如何在方法compareTo中使用方法compareTo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57023336/