2.编程题 使用HashMap<Integer, Book>然后完成下面的功能: 1、放入5 种不同的Book对象,书籍编号作为 key值 2、遍历显示书籍信息 3、使用 remove 移除几个对象 4、再次遍历显示书籍信息
时间: 2024-09-06 21:05:37 浏览: 41
首先,我们需要创建一个`Book`类,并定义一些属性如书名、作者等。然后,我们可以使用`HashMap`来存储书籍对象,其中书名对应的唯一标识将是整数键(Integer key)。以下是实现这个需求的一个示例:
```java
import java.util.*;
class Book {
private int id;
private String title;
private String author;
// 构造函数、getter和setter省略...
@Override
public String toString() {
return "Book{" +
"id=" + id +
", title='" + title + '\'' +
", author='" + author + '\'' +
'}';
}
}
public class HashMapExample {
public static void main(String[] args) {
// 创建HashMap
HashMap<Integer, Book> bookMap = new HashMap<>();
// 放入5种不同的Book对象
Book book1 = new Book(1, "Book A", "Author A");
Book book2 = new Book(2, "Book B", "Author B");
Book book3 = new Book(3, "Book C", "Author C");
Book book4 = new Book(4, "Book D", "Author D");
Book book5 = new Book(5, "Book E", "Author E");
bookMap.put(book1.getId(), book1);
bookMap.put(book2.getId(), book2);
bookMap.put(book3.getId(), book3);
bookMap.put(book4.getId(), book4);
bookMap.put(book5.getId(), book5);
// 遍历显示书籍信息
System.out.println("Books in the map:");
for (Map.Entry<Integer, Book> entry : bookMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue().toString());
}
// 移除几本书
bookMap.remove(book2.getId()); // 假设我们想移除book2
bookMap.remove(book4.getId()); // 假设我们还想移除book4
// 再次遍历显示书籍信息
System.out.println("\nBooks after removal:");
for (Map.Entry<Integer, Book> entry : bookMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue().toString());
}
}
}
```
阅读全文