[英]Instance of class as key in hashmap
我有這個課:
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;
}
}
我想創建一個散列表,其鍵引用類Offer
id和value作為Offer
。
HashMap<id of Offer(?),Offer> repo = new HashMap<id of Offer(?),Offer>();
我怎樣才能做到這一點?
如何分配各Offer
id作為鍵和Offer
上的Hashmap回購值的對象? 我的意思是方法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
它是最新版本,並且更易於使用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.