新建Book书籍类,属性有:id,name,price,type,并将Book类存入map、TreeMap中。分别遍历由HashMap与TreeMap类实现的Map集合,输出书籍对象。
时间: 2023-03-07 14:53:33 浏览: 171
可以使用如下代码来实现:// 定义Book类
public class Book {
private int id;
private String name;
private double price;
private String type; // 省略getter和setter方法 @Override
public String toString(){
return "id:" + id + " name:" + name + " price:" + price + " type:" + type;
}
}// 创建Map集合
Map<Integer, Book> hashMap = new HashMap<>();
TreeMap<Integer, Book> treeMap = new TreeMap<>();// 添加元素
hashMap.put(1, new Book(1, "Java", 79.9, "计算机编程"));
hashMap.put(2, new Book(2, "Python", 69.9, "计算机编程"));
hashMap.put(3, new Book(3, "Web", 59.9, "计算机编程"));treeMap.put(1, new Book(1, "Java", 79.9, "计算机编程"));
treeMap.put(2, new Book(2, "Python", 69.9, "计算机编程"));
treeMap.put(3, new Book(3, "Web", 59.9, "计算机编程"));// 遍历HashMap
for(Map.Entry<Integer, Book> entry: hashMap.entrySet()){
System.out.println("key:" + entry.getKey() + " value:" + entry.getValue());
}// 遍历TreeMap
for(Map.Entry<Integer, Book> entry: treeMap.entrySet()){
System.out.println("key:" + entry.getKey() + " value:" + entry.getValue());
}
阅读全文