我有这门课:
public class Offer {
private Integer id;
private String description;
private Double price;
private String currency;
private Date timeExpired;
public Offer(Integer id, String description, Double price, String currency, Date timeExpired){
this.id = id;
this.description = description;
this.price = price;
this.currency = currency;
this.timeExpired = timeExpired;
}
}
我想创建一个 HashMap ,其键引用类 Offer
的 id,值作为 Offer
。
HashMap<id of Offer(?),Offer> repo = new HashMap<id of Offer(?),Offer>();
我怎样才能做到这一点?
如何在 Hashmap 存储库上将每个 Offer
id 指定为键,将 Offer
对象指定为值?
我的意思是方法 repo.put(?)
最佳答案
因为id是Integer
您需要 HashMap<Integer, Offer>
:
public static void main(String[]args){
HashMap<Integer, Offer> map = new HashMap<Integer, Offer>();
// First way
map.put(1038, new Offer(1038, "foo", 10.20, "bar", new Date()));
// Second way
Offer o1 = new Offer(1038, "foo", 10.20, "bar", new Date());
map.put(o1.getId(), o1);
}
<小时/>
提示:
- 使用
int
和double
而不是Integer
或Double
如果您并不真正需要这些对象 (int vs Integer
) - 使用
LocalDate
而不是Date
这是最新版本,而且更容易使用
关于java - 类的实例作为 hashmap 中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47121064/