文章目录
-
- [1. 题目描述](#1. 题目描述)
- [2. 代码编写](#2. 代码编写)
- [3. 运行截图](#3. 运行截图)
1. 题目描述
(1)定义一个Book类并能根据价格进行比较。(2)创建一个泛型集合存放图书,对图书进行排序并输出。
2. 代码编写
java
package CumtJava;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
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;
}
@Override
public int compareTo(Book other) {
// 对价格进行比较,实现降序排序(从高到低)
if (this.price > other.price) {
return -1;
}
else if (this.price < other.price) {
return 1;
}
else {
return 0;
}
}
}
java
package CumtJava;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class BookSortExample {
public static void main(String[] args) {
List<Book> books = new ArrayList<>(); //集合
books.add(new Book("Book1", 25.0));
books.add(new Book("Book2", 15.0));
books.add(new Book("Book3", 30.0));
books.add(new Book("Book4", 20.0));
// 对图书列表进行排序
Collections.sort(books);
// 输出排序后的图书列表
for (Book book : books) {
System.out.println("Title: " + book.getTitle() + ", Price: " + book.getPrice());
}
}
}