我正在做这个项目,在那里我会得到一些书,并且应该按照以下逻辑对其进行排序:
我试图解决但没有解决,所以我在解决方案中查找:
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);
}
}
我在这里不明白的是这部分“返回this.title.compareTo(specifiedBook.title);”。我们如何在方法compareTo中使用方法compareTo,这不是递归吗,我知道在实现可接口接口时,我们必须重写方法compareTo,但是如何在Overriden compareTo方法中使用compareComp方法呢?在这种情况下以及一般情况下,该怎么办?
让我感到困惑的是,我们如何使用在接口中声明的方法,它不是从父类继承的。它只是在可比较的接口中声明的,因此当我们实现该接口时,必须重写它
答案 0 :(得分:5)
假设title
和author
是字符串,则从String.compareTo
内部调用Book.compareTo
(已实现)。这不是递归。这是另一个类中的方法。
答案 1 :(得分:-1)
使用java.util.Comparator比较字段的最简单,更好的方法。我强烈建议您改写equals和hashCode方法,因为您要将这些书放在某个容器中,该容器可能是Sorted Set或类似的东西。无论如何,这是示例代码,
import org.junit.Test;
import java.util.Comparator;
import java.util.Objects;
import java.util.StringJoiner;
import java.util.TreeSet;
public class BookTest {
@Test
public void compareBooks() {
Book b1 = new Book(100, "A book", "Zoro");
Book b2 = new Book(10, "Small book", "ABC");
TreeSet<Book> books = new TreeSet<>();
books.add(b1);
books.add(b2);
System.out.println(books);
}
private class Book implements Comparable<Book> {
private final int numberOfPages;
private final String title;
private final String author;
private Book(int numberOfPages, String title, String author) {
this.numberOfPages = numberOfPages;
this.title = title;
this.author = author;
}
public int getNumberOfPages() {
return numberOfPages;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
@Override
public int compareTo(Book that) {
return Comparator.nullsFirst(
Comparator.comparing(Book::getNumberOfPages)
.thenComparing(Book::getTitle)
.thenComparing(Book::getAuthor))
.compare(this, that);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Book book = (Book) o;
return numberOfPages == book.numberOfPages
&& title.equals(book.title)
&& author.equals(book.author);
}
@Override
public int hashCode() {
return Objects.hash(numberOfPages, title, author);
}
@Override
public String toString() {
return new StringJoiner(", ", Book.class.getSimpleName() + "[", "]")
.add("numberOfPages=" + numberOfPages)
.add("title='" + title + "'")
.add("author='" + author + "'")
.toString();
}
}
}