0

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(?)

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
SwampThing
  • 125
  • 1
  • 8

1 Answers1

2

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 :

  • use int and double rather than Integer or Double if you don't really need the objects (int vs Integer)
  • use LocalDate instead of Date it's the latest version, and easier to use
azro
  • 53,056
  • 7
  • 34
  • 70
  • Do you think op has a reason to use Integer for their id because they are going to use it as a key in a hashmap? – matt Nov 05 '17 at 11:46
  • @matt: I am going to create a RESTful, I think I need Integer for that, because the compiler complains without it. – SwampThing Nov 05 '17 at 11:50
  • @matt With rest app don't know, but you can add int element in a Map or List ;) – azro Nov 05 '17 at 11:56
  • @azro when you "add an int" element, it is getting autoboxed to an Integer. depending on how often you are doing it, it can help to stick to Integer. Although it sounds like OP needs to use Integer for other reasons. – matt Nov 05 '17 at 12:13