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원)]
'트러블슈팅' 카테고리의 다른 글
| Session 로그인 적용하면서 API 구조 리팩토링하기 (0) | 2026.07.09 |
|---|---|
| [IntelliJ IDEA 기능] Compact Middle Packages / 패키지 설정 (0) | 2026.07.07 |
| [Spring] 전체조회시, 조건 전체조회 (feat.@RequestParam) (0) | 2026.06.30 |
| [Java] Scanner 사용 시 nextInt(); 주의점! (0) | 2026.06.04 |
| 💻 Git 브랜치 작업하면서 겪은 트러블슈팅 정리 (0) | 2026.06.01 |