有一個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;
}
}
其中是OrderLine類。這就是你的代碼所做的。發佈整個代碼,我會建議修復。看起來像c.clearCart()無法清除購物車 – JavaHopper
已添加全部代碼 –
如何在主類的for循環中的SOP中獲取'entry.getValue()。get(0)'? –