【发布时间】:2016-08-05 03:49:41
【问题描述】:
有一个Hashmap(o),它以字符串为键,以Order Object为值。 Order 有一个 OrderLines 的 Arraylist。在这里,我必须向地图添加多个订单。问题是我的哈希图打印出唯一的第一个和第二个键(顺序 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() + "*******");
}
订单类:
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();
}
}
OrderLine 类:
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() 无法清除购物车
-
添加所有代码
-
如何在主类的for循环中的SOP中得到
entry.getValue().get(0)? -
看我的回答。这个问题不应该像现在这样被否决。有足够多的代码来理解这个问题,而答案实际上就在 Java 的幕后工作中。 OP因为不知道问题而找不到答案,这是完全可以理解的。
-
不知道为什么人们拒绝投票
标签: java list arraylist collections hashmap