练习2:用TreeMap类实现向数字图书馆中添加三本书籍,书籍类的属性有书籍编号,书籍名,作者,单价。遍历集合,按照书籍编号排序。(
时间: 2024-11-29 10:39:17 浏览: 13
要在Java中使用TreeMap类实现向数字图书馆添加书籍,并按书籍编号排序,首先需要创建一个Books类,包含书籍编号(bookId)、书籍名称(title)、作者(author)和单价(price)属性。然后,你可以按照以下步骤操作:
1. 定义Books类:
```java
class Books {
private int bookId;
private String title;
private String author;
private double price;
// 构造函数、getter和setter方法
public Books(int bookId, String title, String author, double price) {
this.bookId = bookId;
this.title = title;
this.author = author;
this.price = price;
}
// getters and setters
}
```
2. 创建TreeMap实例,键为书籍编号,值为Books对象:
```java
import java.util.TreeMap;
public class Library {
private TreeMap<Integer, Books> bookCollection = new TreeMap<>();
// 添加书籍方法
public void addBook(Books book) {
bookCollection.put(book.getBookId(), book);
}
}
```
3. 向图书馆添加书籍:
```java
Books book1 = new Books(1, "Book A", "Author A", 19.99);
Books book2 = new Books(2, "Book B", "Author B", 29.99);
Books book3 = new Books(3, "Book C", "Author C", 39.99);
Library library = new Library();
library.addBook(book1);
library.addBook(book2);
library.addBook(book3);
```
4. 遍历并打印书籍列表,按照书籍编号排序:
```java
for (Map.Entry<Integer, Books> entry : library.bookCollection.entrySet()) {
System.out.println("书籍编号: " + entry.getKey() +
", 书名: " + entry.getValue().getTitle() +
", 作者: " + entry.getValue().getAuthor() +
", 单价: " + entry.getValue(). getPrice());
}
```
阅读全文