2016-08-05 32 views
-2

有一個HashMap(O)這需要字符串作爲密鑰和Order對象作爲值。爲了有OrderLines的ArrayList。在這裏,我要多個訂單添加到地圖中。問題是我的HashMap中打印出獨特的第一和第二密鑰(1階和二階2),但最後插入值作爲這兩個鍵的值(副本中的所有條目順序)。你能幫我調試問題嗎?重複的值插入在哈希映射

主類

Map<String, Order> o = new HashMap<String, Order>(); 

    Order c = new Order(); 

    c.add(new OrderLine(new Item("book", (float) 12.49), 1)); 
    c.add(new OrderLine(new Item("music CD", (float) 14.99), 1)); 

    o.put("Order 1", c); 

    // Reuse cart for an other order 
    c.clearCart(); // this.orderLines.clear() in the order class 

    c.add(new OrderLine(new Item("imported box of chocolate", 10), 1)); 
    c.add(new OrderLine(new Item("imported bottle of perfume", (float)  47.50), 1)); 

    o.put("Order 2", c); 

    for (Map.Entry<String, Order> entry : o.entrySet()) { 
     System.out.println("*******" + entry.getKey() + entry.getValue().get(0).getItem().getDescription() + "*******"); 
    } 

Order類

class Order { 

private List<OrderLine> orderLines = new ArrayList<>(); 

public void add(OrderLine o) throws Exception { 
    orderLines.add(o); 
} 

public OrderLine get(int i) { 
    return orderLines.get(i); 
} 

public void clearCart() { 
    this.orderLines.clear(); 
} 
} 

訂單行類:

private int quantity; 
private Item item; 

public OrderLine(Item item, int quantity) throws Exception { 
    if (item == null) { 
     System.err.println("ERROR - Item is NULL"); 
     throw new Exception("Item is NULL"); 
    } 
    assert quantity > 0; 
    this.item = item; 
    this.quantity = quantity; 
} 

public Item getItem() { 
    return item; 
} 

public int getQuantity() { 
    return quantity; 
} 
} 

項目類:

class Item { 

    private String description; 
    private float price; 

    public Item(String description, float price) { 
     super(); 
     this.description = description; 
     this.price = price; 
    } 

    public String getDescription() { 
     return description; 
    } 

    public float getPrice() { 
     return price; 
    } 
    } 
+0

其中是OrderLine類。這就是你的代碼所做的。發佈整個代碼,我會建議修復。看起來像c.clearCart()無法清除購物車 – JavaHopper

+0

已添加全部代碼 –

+0

如何在主類的for循環中的SOP中獲取'entry.getValue()。get(0)'? –

回答

2

雖然Java是傳遞的價值,它是完全有效的改變在參考的到底是什麼的。這是你在做什麼,儘管在不經意間。

想想你在做什麼:將c添加到列表中,然後清除c,重新初始化它,並再次添加它。

正如你從來不使用new關鍵字,你從來沒有真正分配的內存c.一個新的部分它仍然指向同一Order.同時,你沒有的c克隆添加到列表中。您添加c.

換句話說,當你調用c.clearCart(),你也在名單o清空第一Order作爲所述Orderc.

您既可以通過更換使用new關鍵字:

c.clearCart(); 

c = new Order(); 

或者,你可以添加的c克隆列出o而不是c本身,所以,當你調用c.clearCart(),你是不是在名單o.換句話說結算的第一要素,取代:

o.put("Order 1", c); 

o.put("Order 1", c.clone()); 

查看this question瞭解更多信息。

編輯:

我忘了其中的一部分,儘管它可能是顯而易見的。我說,清理c也將清除的第一個元素列表o,,因爲該元素c.不過,我忘了提及的是,通過轉型,重新初始化c 也意味着同時重新初始化這個元素。因此,當您再次添加c時,您有兩個使用相同字段初始化的元素。