2015-02-05 30 views
0

我目前有兩個類。 主營:從一個HashMap複製一個搜索的對象和密鑰到另一個

public class Main { 

    HashMap <String, Product> products = new HashMap<String, Product>(); 

    public Main() { 

     products.put("Cel403", (new Product("Chocolate sundae", 5.99))); 
     products.put("Pi342", (new Product("Baseball Bat", 1.50))); 
    } 

    public void scan(String id) { 

    } 

產品:

public class Product { 
    private String descr; 
    private double price; 

    public Product(String descr, double cost) { 
     this.descr = descr; 
     this.cost = cost; 
    } 

    public String toString() { 
     return (" Description: " + descr + " Cost: " + cost); 

我現在有一個產品HashMap中設置了一個產品ID作爲字符串,產品類作爲該實體(項目的描述,價格項目)。

我想創建一個方法,我已經開始設置,稱爲掃描方法。這將允許在參數中輸入一個id(「Cel403」或「Pi342」),然後查看HashMap(也許是一個迭代器?)並檢索它匹配的條目(Product)。 我想要它然後複製(id)字符串和附加產品對象到另一個名爲'掃描'的HashMap。 然後,我可以多次運行掃描方法,將更多產品添加到新創建的「掃描」HashMap中。然後,「掃描的」HashMap將包含帶有ID的掃描對象,並且我將能夠計算掃描的HashMap中項目的總成本。 這可能嗎?我將如何去做這件事。

+0

是的,這是可能的。 – 2015-02-05 14:57:52

+0

我該如何去做呢? – Ju5476 2015-02-05 14:59:31

+0

@Reddax你有什麼試過嗎?您應該共享有關您當前設計的更多細節(用於此計算)。 – 2015-02-05 15:07:27

回答

0

由於Map鍵必須是唯一的,所以如果按照您所描述的操作,則每個產品ID只能獲得一個條目。如果這是你在找什麼,你應該做這樣的事情

Map <String, Product> scanned = new HashMap<String, Product>(); 

public void scan(String id) { 
    scanned.put(id, products.get(id)); 
} 

因爲我懷疑這是你需要什麼,你倒是應該使掃描包含掃描產品或者對商品的列表,它的ID。

+0

正是我想要的。哇,那很容易。非常感謝。 – Ju5476 2015-02-05 15:10:44

+0

我將如何去獲取掃描產品中的所有價格,並將它們加在一起? – Ju5476 2015-02-05 15:13:04

+0

雙重總計= 0.0; (產品項目:已掃描){ total + = item.getPrice(); } – 2015-02-05 15:16:14

相關問題