类的实例作为hashmap中的键

时间:2017-11-05 11:33:31

标签: java hashmap instance

我有这堂课:

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

1 个答案:

答案 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),请使用intdouble而不是IntegerDouble
  • 使用LocalDate代替Date这是最新版本,更易于使用