본문 바로가기
스파르타 내일배움캠프/TIL(Today I learned)

25.03.12 TIL - 컬렉션

by pandastic 2025. 3. 12.
반응형

 

 

목차

     

     

    1. Chapter 3 - 3 : 컬렉션(Collection)

    1. 컬렉션

        - 자바 컬렉션 프레임워크는 자료구조들을 쉽게 사용할 수 있도록 인터페이스와 구현체(ArrayList, HashSet, HashMap) 등을 제공하는 집합.

        - 컬렉션을 통해 데이터 저장, 조회, 삭제, 정렬 등 다양한 기능을 간편하게 구현 가능.

        - 배열과 다르게 컬렉션은 길이를 동적으로 변경 가능. (추가/ 삭제 시 유연하게 길이가 변경됨)

     

    ※ 배열의 한계

        - 배열은 크기가 고정되어 있어 한 번 설정하면 길이 변경 불가 → 배열의 길이 초과 시 에러 발생.

        - 자바에서 다양한 컬렉션 클래스(ArrayList, HashSet, HashMap 등) 제공.

        - 컬렉션 객체를 활용해 데이터들을 저장하고 관리 가능.

    // 배열은 길이가 고정됨
    int[] numbers = new int[3];
    numbers[0] = 10;
    numbers[1] = 20;
    numbers[2] = 30;
    numbers[3] = 40; // ❌ 요소 추가시 에러발생

     

     

    [선언 방법]

    컬렉션객체<자료형> 변수이름 = new 컬렉션객체<자료형>();
    // 객체<다룰 데이터: 정수> 변수이름 = new 컬렉션객체생성자<정수>();
    ArrayList<Integer> arrayList = new ArrayList<Integer>();

     

    // 컬렉션
    // 인스턴스화 시킬 때 사용하는 new 키워드
    // ArrayList 라는 클래스를 인스턴스화 시켜서 arrayList라는 변수에 넣어주고 있는 것.
    // < 자료형 > == 제네릭
    // 뒤에 있는 < 자료형 > 은 생략 가능함 -> 앞의 자료형을 따라가기 때문.
    ArrayList<Integer> arrayList = new ArrayList<>();
    arrayList.add(10);
    arrayList.add(20);
    arrayList.add(30);
    arrayList.add(40); // ✅ 정상 동작 (길이 제한 없음)

       - 배열과 다르게 컬렉션은 길이를 동적으로 변경 가능.

     

     

    📖 컬렉션 종류와 특징

    인터페이스 특징 구현체
    List 순서 유지, 중복 허용 ArrayList
    Set 순서 없음, 중복 불가 HashSet
    Map 키-값 구조, 키 중복 불가 HashMap

     

     

    1) List 인터페이스를 구현한 ArrayList

      - ArrayList는 요소의 순서를 유지하고 중복된 값을 저장할 수 있는 자료 구조.

      - 요소 추가 → add("값")

      - 요소 조회 → get(인덱스)

      - 요소 제거 → remove("값")

      - 대표적인 구현체로는 ArrayList, LinkedList가 있음.

     

    [예시 코드]

    // List 를 구현한 ArrayList
    ArrayList<String> names = new ArrayList<>();
    names.add("Spartan");      // 1 번째 요소 추가
    names.add("Steve");        // 2 번째 요소 추가
    names.add("Isac");         // 3 번째 요소 추가
    names.add("1");
    names.add("2");
     // ✅ 순서 보장
    System.out.println("names = " + names);
    // ✅ 중복 데이터 허용
    names.add("Spartan");
    System.out.println("names = " + names);
    // ✅ 단건 조회
    System.out.println("1 번째 요소 조회: " + names.get(0)); // 조회 Spartan
    // ✅ 데이터 삭제
    names.remove("Steve"); 
    System.out.println("names = " + names);

     

     

    2) Set 인터페이스를 구현한 HashSet

        - HashSet은 순서를 유지하지 않고 중복을 허용하지 않음.

          → 순서를 보장하지 않기 때문에 get() 지원하지 않음.

        - 요소 추가 → add("값")

        - 요소 제거 → remove("값")

        - 대표적인 구현체로는 HashSet, TreeSet이 있음.

     

    [예시코드]

    // Set 을 구현한 HashSet
    HashSet<String> uniqueNames = new HashSet<>();
    // ✅ 추가
    uniqueNames.add("Spartan");
    uniqueNames.add("Steve");
    uniqueNames.add("Isac");
    uniqueNames.add("1");
    uniqueNames.add("2");
    // ⚠️ 순서를 보장 안함
    System.out.println("uniqueNames = " + uniqueNames); 
    uniqueNames.get(0); // ❌ get 사용 불가
    // ⚠️ 중복 불가
    uniqueNames.add("Spartan");
    System.out.println("uniqueNames = " + uniqueNames); 
    // ✅ 제거
    uniqueNames.remove("Spartan");
    System.out.println("uniqueNames = " + uniqueNames);

     

     

    3) Map 인터페이스를 구현한 HashMap

        - HashMap은 키(key) - 값(value) 구조로 데이터를 저장함.

        - 키(key)는 중복될 수 없지만 값(value)는 중복 가능.

        - 순서를 보장하지 않음.

        - 요소 추가 → put("키", 값)

        - 요소 조회 → get("키")

        - 요소 제거 → remove("Steve")

        - 키 확인 → keySet()

        - 값 확인 → values()

        - 대표적인 구현체로는 HashMap, TreeMap이 있음.

     

    [예시 코드]

    // Map 을 구현한 HashMap
    HashMap<String, Integer> memberMap = new HashMap<>();
    // ✅ 추가
    memberMap.put("Spartan", 15);
    memberMap.put("Steve", 15); // ✅ 값은 중복 가능
    memberMap.put("Isac", 1);
    memberMap.put("John", 2);
    memberMap.put("Alice", 3);
    // ⚠️ 순서 보장 안함 
    System.out.println("memberMap = " + memberMap);
    // ⚠️ 키 중복 불가: 값 덮어쓰기 발생
    memberMap.put("Alice", 5);
    System.out.println("memberMap = " + memberMap);
    // ✅ 조회: 15
    // 단 건 조회
    // 인덱스로 접근하는 것이 아니라 key로 접근하게 됨.
    // key로 접근하게 되면 반환되는 데이터는 그 key에 해당하는 값이 반환되게 됨.
    System.out.println(memberMap.get("Steve"));
    // ✅ 삭제 가능
    memberMap.remove("Spartan"); 
    System.out.println("memberMap = " + memberMap);
    // ✅ 키 확인
    Set<String> keys = memberMap.keySet();
    System.out.println("keys = " + keys);
    // ✅ 값 확인
    Collection<Integer> values = memberMap.values();
    System.out.println("values = " + values);

     

     

     

    [실습 과제]

    더보기

    💬 Q1. ArrayList 로 장바구니를 구현해 보세요.

    💡요구사항

    • 장바구니 상품: 양파, 사과, 생선, 두부
    • 기능1: 상품추가(addProduct)
    • 기능2: 장바구니 목록 출력(printCart)
    • 기능3: 상품 삭제(removeProduct)
    • 기능4: 총 가격 계산(calculateTotalPrice )

     

    정답)

    Product.java

    public class Product {
        // 속성
        private String name;
        private int price;
    
        // 생성자
        public Product(String name, int price) {
            this.name = name;
            this.price = price;
        }
    
        // 기능
        public String getName() {
            return this.name;
        }
    
        public int getPrice() {
            return this.price;
        }
    }

     

    Cart.java

    import java.util.ArrayList;
    import java.util.List;
    
    public class Cart {
    
        // 속성
        private List<Product> cart = new ArrayList<>();
    
        // 생성자
    
        // 기능
        // 상품 추가 기능
        public  void addProduct(Product product) {
            cart.add(product);
            System.out.println(product.getName() + " 가 장바구니에 추가 되었습니다.");
        }
    
        // 상품 제거 기능
        public void removeProduct(String removeProductName) {
            boolean removed = false;
    
            for (Product product : cart) {
                String foundProductName = product.getName();
                if (foundProductName.equals(removeProductName)) {
                    cart.remove(product);
                    System.out.println(product.getName() + "가 장바구니에서 제거 되었습니다.");
                    break;
                }
            }
            if (!removed) {
                System.out.println("해당 상품이 장바구니에 없습니다.");
            }
        }
    
        // 장바구니 목록 출력 기능
        public void printCart() {
            if (cart.isEmpty()) {
                System.out.println("장바구니가 비어 있습니다.");
            } else {
                for (Product product : cart) {
                    System.out.println(product.getName() + ": " + product.getPrice());
                }
            }
        }
    
        // 장바구니 총 상품 가격 조회 기능
        public void calculateTotalPrice() {
            int total = 0;
            for (Product product : cart) {
                total += product.getPrice();
            }
            System.out.println("총 금액은: " + total);
        }
    }

     

    Main.java

    public class Main {
    
        public static void main(String[] args) {
    
            Cart cart = new Cart();
            Product onion = new Product("양파", 3000);
            Product apple = new Product("사과", 10000);
            Product fish = new Product("생선", 12000);
            Product tofu = new Product("두부", 2000);
    
    
            // 장바구니에 상품 추가
            System.out.println("장바구니 상품 추가: ");
            cart.addProduct(onion);
            cart.addProduct(apple);
            cart.addProduct(fish);
            cart.addProduct(tofu);
            System.out.println();
    
            //  장바구니 상품 조회
            System.out.println("장바구니 상품 조회: ");
            cart.printCart();
            System.out.println();
    
            // 장바구니 총 금액 조회
            System.out.println("장바구니 총 금액 조회: ");
            cart.calculateTotalPrice();
            System.out.println();
    
            // 장바구니 상품 제거(사과)
            System.out.println("장바구니에서 사과 제거: ");
            cart.removeProduct("사과");
            System.out.println();
    
            //  장바구니 상품 조회
            System.out.println("장바구니 상품 조회: ");
            cart.printCart();
            System.out.println();
    
            // 장바구니 총 금액 조회
            System.out.println("장바구니 총 금액 조회: ");
            cart.calculateTotalPrice();
            System.out.println();
        }
    }
    반응형