定义一个Book类并能根据价格进行比较。创建一个泛型集合存放图书,对图书进行排序并输出。
时间: 2024-03-08 16:49:31 浏览: 60
好的,下面是代码示例:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Book implements Comparable<Book> {
private String title;
private double price;
public Book(String title, double price) {
this.title = title;
this.price = price;
}
// getter and setter methods
@Override
public int compareTo(Book o) {
return Double.compare(this.price, o.price);
}
public static void main(String[] args) {
List<Book> books = new ArrayList<>();
books.add(new Book("The Catcher in the Rye", 20.0));
books.add(new Book("To Kill a Mockingbird", 15.0));
books.add(new Book("Pride and Prejudice", 25.0));
books.add(new Book("1984", 18.0));
books.add(new Book("The Great Gatsby", 30.0));
System.out.println("Before sorting:");
for (Book book : books) {
System.out.println(book.getTitle() + " - $" + book.getPrice());
}
// sort by price using Comparable interface
Collections.sort(books);
System.out.println("\nAfter sorting by price:");
for (Book book : books) {
System.out.println(book.getTitle() + " - $" + book.getPrice());
}
// sort by price using Comparator interface
Comparator<Book> priceComparator = new Comparator<Book>() {
@Override
public int compare(Book o1, Book o2) {
return Double.compare(o1.getPrice(), o2.getPrice());
}
};
Collections.sort(books, priceComparator);
System.out.println("\nAfter sorting by price using Comparator:");
for (Book book : books) {
System.out.println(book.getTitle() + " - $" + book.getPrice());
}
}
}
```
这个示例中,我们定义了一个 `Book` 类,并实现了 `Comparable` 接口,这个接口用于定义比较规则,这里我们按照价格进行比较。
在 `main` 方法中,我们创建了一个泛型集合 `List<Book>`,并添加了几本书。然后,我们使用 `Collections.sort` 方法对集合进行排序,排序时会调用 `Book` 类的 `compareTo` 方法进行比较。
在排序之后,我们输出了排序后的结果。同时,我们还演示了如何使用 `Comparator` 接口定义比较规则,然后使用这个规则对集合进行排序。
阅读全文