簡體   English   中英

類實例作為哈希圖中的鍵

[英]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);

}

提示 :

  • 如果您確實不需要對象,則使用intdouble而不是IntegerDoubleint vs Integer
  • 使用LocalDate代替Date它是最新版本,並且更易於使用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM