Reputation: 125
I have this class:
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;
}
}
I want to create a hashmap with key that refers to id of the class Offer
and value as Offer
.
HashMap<id of Offer(?),Offer> repo = new HashMap<id of Offer(?),Offer>();
How can I do that?
How assign each Offer
id as key and the Offer
objects as values on Hashmap repo?
I mean method repo.put(?)
Upvotes: 0
Views: 964
Reputation: 54148
Because the id is an Integer
your need a 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);
}
Tips :
int
and double
rather than Integer
or Double
if you don't really need the objects (int vs Integer
)LocalDate
instead of Date
it's the latest version, and easier to useUpvotes: 2