2 回答
TA贡献1802条经验 获得超4个赞
假设title
和author
是字符串,您正在String.compareTo
从内部调用(已经实现)Book.compareTo
。这不是递归。这是不同类中的方法。
TA贡献1796条经验 获得超4个赞
使用 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();
}
}
}
添加回答
举报