내일배움캠프 12일차 TIL - 컬렉션

iy·2024년 1월 1일

TIL

목록 보기
11/37

컬렉션

  • 기능 : 크기 자동조절/ 추가/ 수정/ 삭제/ 반복/ 순회/ 필터/ 포함확인 등...

    • 배열은 길이를 꼭 입력해야하는데 모르고 배열을 선언하고 싶을 때 자동조절이 가능한 collection을 사용하면 됨
  • 컬렉션 종류

    • List : 순서가 있는 데이터의 집합(데이터 중복 허용)-배열과 비슷
    • Queue : 빨대처럼 한쪽에서 데이터를 넣고 반대쪽에서 데이터를 뺄 수 있는 집합
      • First In First Out : 먼저 들어간 순서대로 값을 조회할 수 있다.
    • Set : 순서가 없는 데이터의 집합(데이터 중복 허용 안 함) - 순서가 없고 중복없는 배열
    • Map : 순서가 없는(Key,Value) 쌍으로 이루어진 데이터의 집합(Key값 중복 허용 안함)
  • Collection은 기본형 변수가 아닌 참조형 변수를 저장

    • int의 참조형 변수 : Integer
    • long의 참조형 변수 : Long
    • double의 참조형 변수 : Double
    • String은 원래부터 참조형 변수

  1. List
  • List는 순서가 있는 데이터의 집합
  • Array는 처음에 길이를 알아야 하지만 List는 처음에 길이를 몰라도 만들 수 있음
    - Array : 정적배열
    - List : 동적배열(크기가 가변적으로 늘어남)
      - 생성 시점에 작은 연속된 공간을 요청해서 참조형 변수들을 담아놓음
      - 값이 추가될 때 더 큰 공간이 필요하면 더 큰 공간을 받아서 저장함
        ArrayList<Integer> intList = new ArrayList<Integer>(); // 선언 + 생성
        intList.add(99);
        intList.add(15);
        intList.add(3);

//        System.out.println(intList.get(1));

        // 두번째 있는 값(15)를 바꿔보자
//        intList.set(1,10);
//        System.out.println(intList.get(1));

        System.out.println(intList.get(0));

        // 삭제
        intList.remove(0);
        System.out.println(intList.get(0));

        //전체 삭제 전 리스트 보기
        System.out.println(intList.toString());
        //전체 삭제메서드 : clear()
        intList.clear();
        //삭제 후 전체 조회
        System.out.println(intList.toString());
  1. Linked List
  • 메모리에 남는 공간을 요청해서 나누어 실제 값을 달아놓음
  • 실제 값에 있는 주소값으로 목록을 구성하고 저장하는 자료구조
  • 기본적으로 기능은 ArrayList와 동일함
  • LinkedList는 여기저기 나누어 값을 담아두기 때문에 조회 속도는 느림
  • 값 추가나 삭제 때는 빠름!
        LinkedList<Integer> linkedList = new LinkedList<Integer>();

        linkedList.add(5);
        linkedList.add(10);
        linkedList.add(3);

        System.out.println(linkedList.get(0));
        System.out.println(linkedList.get(1));
        System.out.println(linkedList.get(2));

        System.out.println(linkedList.toString()); // 조회할 때 ArrayList보다 느리다

        linkedList.add(200);
        System.out.println(linkedList.toString()); //200이라는 요소 추가

        linkedList.add(2,4);
        System.out.println(linkedList.toString()); // 인덱스 2번에 4라는 요소 추가

        linkedList.set(1,30);
        System.out.println(linkedList.toString());

        linkedList.remove(1);
        System.out.println(linkedList.toString());

        linkedList.clear();
        System.out.println(linkedList.toString());
  1. Stack
  • 수직으로 값을 쌓아놓음
  • push(값 추가), peek(맨 위에 값 조회), pop(맨 위에 값 삭제)
  • 최근 저장된 데이터를 나열하고 싶거나 데이터의 중복 처리를 막고 싶을 때 사용
        Stack<Integer> intStack = new Stack<Integer>();

        intStack.push(10);
        intStack.push(15);
        intStack.push(1);

        // 다 지워질 때 까지 출력
        while (!intStack.isEmpty()){
            System.out.println(intStack.pop()); // push로 쌓아놓았던 것 pop이 실행되면서 위에부터 출력
            // 1 -> 15 -> 10
        }

        // 다시 추가
        intStack.push(10);
        intStack.push(15);
        intStack.push(1);

        // peek
        System.out.println(intStack.peek());
        System.out.println(intStack.size());
  1. Queue
  • FIFO
  • 메소드 : add, peek, poll(맨 위에 값 삭제)
  • Queue : 생성자가 없는 인터페이스
    - new로 생성 불가능
        Queue<Integer> intQueue = new LinkedList<>(); // Queue 선언, 생성

        intQueue.add(1);
        intQueue.add(5);
        intQueue.add(9);

        while (!intQueue.isEmpty()){
            System.out.println(intQueue.poll());
        }

        // 다시 추가
        intQueue.add(1);
        intQueue.add(5);
        intQueue.add(9);
        intQueue.add(10);

        // peek
        System.out.println(intQueue.peek());
        System.out.println(intQueue.size());
  1. Set
  • Set(집합) : 순서 없고, 중복 없음
  • 순서가 보장되지 않는 대신 중복을 허용하지 않도록 하는 프로그램에서 사용할 수 있는 자료구조
  • Set -> 그냥 쓸 수도 있지만 HashSet, TreeSet 등으로 응용해서 같이 사용 가능
  • Set을 생성자가 없는 껍데기라서 바로 생성 불가능
  • 생성자가 존재하는 HashSet을 이용해서 Set을 구현 가능
        Set<Integer> intSet = new HashSet<>(); // 선언 및 생성

        intSet.add(1);
        intSet.add(12);
        intSet.add(5);
        intSet.add(9);
        intSet.add(2);
        intSet.add(12);

        for (Integer value : intSet){
            System.out.println(value);
        }

        //contains
        System.out.println(intSet.contains(2));
        System.out.println(intSet.contains(5));
  1. Map
  • Map : (key , value)로 값을 저장
  • key라는 값으로 unique하게 보장이 되야 함
  • Map -> HashMap, TreeMap으로 응용
        Map<String,Integer> intMap = new HashMap<>();

        // 키값
        intMap.put("일",11);
        intMap.put("이",12);
        intMap.put("삼",13);
        intMap.put("삼",14);//중복 키값
        intMap.put("삼",15);//중복 키값

        // Key값 전체 출력(향상된 for문)
        for (String key: intMap.keySet()){
            System.out.println(key);// 중복이 제거되고 출력 : 3
        }

        // Value값 전체 출력(향상된 for문)
        for (Integer value: intMap.values()){
            System.out.println(value);// 중복이 제거되고 출력 : 12, 11,15 증벅값 중 마지막으로 덮어씀
        }

        System.out.println(intMap.get("삼"));

👀
많이 사용하지 않았던 부분을 배워서 시간이 좀 오래 걸렸다 상황에 맞게 잘 사용하려면 우선 오늘 공부한 collection의 특징을 잘 알아둬야 할 거 같다.

😥 반성..
원래는 1월 1일까지 강의를 다 듣고 싶었는데 예기치 않게 생긴 일정과 이해하는 데 좀 걸리는 부분에서 시간이 많이 걸렸다.. 또 돌이켜보니 1일까지 1회독 목표는 조금 무리였던 거 같다..... 앞으로는 목표와 계획을 잘 세워서 성취감 가져가면서 공부하고 싶다!

📝 다시 세워보는 계획
남은 강의의 시간이 8시간 정도 된다 듣고 끝내기보다 공부하는 시간도 같이 갖는 게 좋을 거 같아서 1월 3일까지 다 들어보도록 하겠다!

0개의 댓글