2017-11-05 2 views
0

でキーとして、私はこのクラスを持っている:は、ハッシュマップ

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としてクラスOfferと値のIDを参照キーでハッシュマップを作成したいです。

HashMap<id of Offer(?),Offer> repo = new HashMap<id of Offer(?),Offer>(); 

どうすればいいですか?

それぞれOfferのIDをキーとして割り当て、OfferのオブジェクトをHashmap repoの値として割り当てる方法を教えてください。 idはHashMap<Integer, Offer>Integerあなたの必要性ですので、私は、メソッドrepo.put

+2

'のHashMap <整数、オファー>'が悪いのか? –

+2

'HashMap ' – Oleg

+3

'Repo.put(offer.getId()、offer)' – Oleg

答えて

2

を意味する:

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); 

} 

ヒント:むしろIntegerより

  • 使用intdouble(?)実際にオブジェクトが必要ない場合はDoubleとなります(int vs Integer
  • 0123使用する
  • 代わりに使用DateLocalDateそれは、最新バージョンのだと簡単に
+0

オペレーションはハッシュマップのキーとして使用するため、IDにIntegerを使用する理由があると思いますか? – matt

+0

@matt:私はRESTfulを作成しようとしていますが、コンパイラはそれがなくても不平を言うので、Integerが必要です。 – SwampThing

+0

@matt残念なことにアプリケーションではわかりませんが、「」または「」のリストにint要素を追加することができます。 – azro