2016-08-05 3 views
-2

문자열을 키로, 오더 오브젝트를 값으로 사용하는 해시 맵 (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; 
    } 
    } 
+0

여기서는 OrderLine 클래스입니다. 그것이 코드가하는 방식입니다. 전체 코드 게시, 수정 제안합니다. c.clearCart()가 장바구니를 지울 수없는 것 같습니다 – JavaHopper

+0

모든 코드가 추가되었습니다 –

+0

메인 클래스의 for 루프에있는 SOP에서'entry.getValue(). get (0)'을 어떻게 얻을 수 있습니까? –

답변

2

자바 패스에 의해 값이지만,이 참조의 끝에서 무엇을 변경 완벽하게 유효합니다. 이것은 우연히 당신이하는 일입니다.

당신이하고있는 일에 대해 생각해보십시오. c을 목록에 추가 한 다음 c,을 다시 초기화하고 다시 추가하십시오. 당신이 new 키워드를 사용하지 않을 것처럼

, 당신은 결코 실제로 그것은 여전히 ​​동시에 같은 Order. 가리키는 c. 메모리의 새로운 부분을 할당하지있어, 당신은 목록에 c의 복제를 추가하지 않았다.

을 : Order c.

당신은 대체하여 new 키워드를 사용할 수 중 하나입니다 말했듯이 당신은 당신이 호출 할 때 c.clearCart(), 당신은 또한 목록 o의 첫 번째 Order을 삭제하고, 즉 c.

추가

c.clearCart(); 

c = new Order(); 

또는, 당신은 당신이 호출 할 때 c.clearCart(), 다른 말로 목록 o.에서 첫 번째 요소를 삭제하지 않도록, 대신 c 자체의 o을 나열 c의 복제를 추가 할 수 있습니다 대체 :

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

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

자세한 내용은 this question을 참조하십시오.

편집 :

내가 그것을 분명있을 수 있지만, 한 부분을 잊어 버렸습니다.나는 c을 지우면 목록 o,의 첫 번째 요소가 지워질 것이라고 언급했는데 그 이유는 해당 요소가 c.이기 때문입니다. 그러나 전환을 통해 다시 초기화하는 것을 잊었습니다. c 은이 요소를 동시에 다시 초기화한다는 의미입니다. 결과적으로 c을 다시 추가하면 동일한 필드로 초기화 된 두 개의 요소가 생깁니다.

관련 문제