我有这堂课:
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>();
我该怎么做?
如何将每个Offer
ID分配为关键字,将Offer
个对象分配为Hashmap repo上的值?
我的意思是方法repo.put(?)
答案 0 :(得分:2)
因为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 vs Integer
),请使用int
和double
而不是Integer
或Double
LocalDate
代替Date
这是最新版本,更易于使用