문자열을 키로, 오더 오브젝트를 값으로 사용하는 해시 맵 (o)이 있습니다. 주문에는 주문 행의 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() + "*******");
}
주문 클래스 :
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()가 장바구니를 지울 수없는 것 같습니다 – JavaHopper
모든 코드가 추가되었습니다 –
메인 클래스의 for 루프에있는 SOP에서'entry.getValue(). get (0)'을 어떻게 얻을 수 있습니까? –