트러블슈팅

ArrayList 기반 장바구니 구현

chungmani 2026. 6. 16. 20:39

1. 문제 발견

처음엔 내가 만든 Product 클래스를 <> 자료형에 넣을 수 있다는 생각을 아예 못함..

그래서 밤티같이 아래 코드처럼 침 ;; 

ArrayList<String> items;
ArrayList<Integer> prices;
 
딱봐도 이건 아닌것 같은데 라는 느낌이 와서.. 짱구를 굴려봄
아 이거 Product 넣어도 되는거 아닌가 어차피 참조형 변수니까로 해결 
 
 

그리고 장바구니 목록 출력하니깐 이래 나옴;; 

바로 내용을 보여줄 줄 알았는데 참조 주소값이 나옴..

collection.Product@3e25a5
 

 


 

 

초기 구조 (잘못된 방향)

ArrayList<String> items;
ArrayList<Integer> prices;
 

 

객체로 묶는 방식으로 변경

public class Product {
    private String item;
    private int price;

    public Product(String item, int price) {
        this.item = item;
        this.price = price;
    }
}
 

 

Cart 설계

public class Cart {
    ArrayList<Product> items = new ArrayList<>();

    public void addProduct(Product p) {
        items.add(p);
    }

    public void removeProduct(Product p) {
        items.remove(p);
    }
}
 

출력 문제 해결 과정

장바구니 목록 출력은 참조 주소값이 나옴...

System.out.println(items);

 

출력 결과

collection.Product@3e25a5
 

 

해결: toString() 오버라이딩

클래스의 최고조상인 Object 형님의 메서드 중에 toString()을 재정의 하는걸로 해결함

@Override
public String toString() {
    return item + "(" + price + "원)";
}
 

출력 결과

[사과(2000원), 양파(1000원)]