用Java编程定义一个Book类并能根据价格进行比较。创建一个泛型集合存放图书,对图书进行排序并输出。
时间: 2024-03-10 18:45:11 浏览: 70
好的,以下是Java代码实现:
```
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class Book implements Comparable<Book> {
private String title;
private double price;
public Book(String title, double price) {
this.title = title;
this.price = price;
}
public String getTitle() {
return title;
}
public double getPrice() {
return price;
}
public void setTitle(String title) {
this.title = title;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public int compareTo(Book book) {
if (this.price > book.price) {
return 1;
} else if (this.price < book.price) {
return -1;
} else {
return 0;
}
}
public static void main(String[] args) {
ArrayList<Book> books = new ArrayList<>();
books.add(new Book("Java Programming", 39.99));
books.add(new Book("Python Programming", 29.99));
books.add(new Book("C++ Programming", 49.99));
books.add(new Book("Data Structures and Algorithms", 59.99));
books.add(new Book("Database Systems", 69.99));
Collections.sort(books);
System.out.println("Sorted by price (ascending order):");
for (Book book : books) {
System.out.println(book.getTitle() + " - $" + book.getPrice());
}
Collections.sort(books, new Comparator<Book>() {
@Override
public int compare(Book book1, Book book2) {
return book2.getTitle().compareTo(book1.getTitle());
}
});
System.out.println("\nSorted by title (descending order):");
for (Book book : books) {
System.out.println(book.getTitle() + " - $" + book.getPrice());
}
}
}
```
在这个例子中,我们定义了一个`Book`类,它有一个`title`属性和一个`price`属性,以及一个比较价格的`compareTo`方法。我们还创建了一个`ArrayList`来存放书籍,然后使用`Collections.sort`方法对其进行排序。在第一次排序中,我们使用默认的价格比较方法来对图书进行排序(升序)。在第二次排序中,我们使用自定义的标题比较方法对图书进行排序(降序)。最后,我们打印出每个图书的标题和价格来验证排序是否正确。
阅读全文