[내배캠]자바 문법 뽀개기-컬렉션

손홍서·2022년 5월 17일
0

Java

목록 보기
4/11
post-thumbnail

컬렉션

컬렉션이란?

다수의 데이터를 다루기 위한 자료구조를 표현하고 사용하는 클래스의 집합 의미
Collection 은 모든 자료구조가 구현(implement)하는 인터페이스
모든 자료구조에 해당하는 클래스, 인터페이스는 언제나 Collection 인터페이스를 구현하고 있다.

  1. list
    순서가 있는 나열된 데이터 표현
    ArrayList는 배열을 이용해 데이터를 저장하는 인터페이스
public class ListPrac {
    public static void main(String[] args) {
    	//정의
        List<Integer> integerList = new ArrayList<>();
        integerList.add(1);
        integerList.add(5);
        integerList.add(2);
        integerList.add(11);
        integerList.add(10);
        integerList.add(3);
        System.out.println(integerList);
        
        //정렬
        System.out.println("-------정렬-------");
        Collections.sort(integerList);
        System.out.println(integerList);
        
        //크기
        System.out.println("integerList.size() = " + integerList.size());
        
        //삭제
        System.out.println("-------i=2 삭제-------");
        integerList.remove(2);
        System.out.println(integerList);
        System.out.println("integerList.size() = " + integerList.size());
        
        //전체 출력
        System.out.println("-------전체 출력(for-each)-------");
        for (int i : integerList) {
            System.out.println(i);
        }
        System.out.println("-------전체 출력(get)-------");
        for (int i = 0; i < integerList.size(); i++) {
            System.out.println(integerList.get(i));
        }

    }
}

  1. set
    순서를 유지하지 않는 데이터 집합이면 데이터 중복 허용 X
    HashSet은 Set 인터페이스를 구현한 대표적인 컬렉션
public class SetPrac {
    public static void main(String[] args) {
        //set 정의
        Set<Integer> integerSet = new HashSet<>();
        integerSet.add(1);
        integerSet.add(1);
        integerSet.add(2);
        integerSet.add(9);
        integerSet.add(4);
        integerSet.add(3);
        integerSet.add(8);
        System.out.println("integerSet = " + integerSet);

        Set<String> stringSet = new HashSet<>();
        stringSet.add("LA");
        stringSet.add("New York");
        stringSet.add("San Francisco");
        stringSet.add("Vegas");
        stringSet.add("D.C.");
        stringSet.add("Seoul");
        System.out.println("stringSet = " + stringSet);

        //하나 지우기
        stringSet.remove("Seoul");
        System.out.println("stringSet = " + stringSet);

        //여러개 지우기
        List<String> target = new ArrayList<>();
        target.add("New York");
        target.add("LA");
        stringSet.removeAll(target);
        System.out.println("stringSet = " + stringSet);

        //포함
        System.out.println("LA가 포함되어있나요? " + stringSet.contains("LA"));
        System.out.println("Vegas가 포함되어있나요? " + stringSet.contains("Vegas"));

        //사이즈
        System.out.println("stringSet.size() = " + stringSet.size());

    }
}


3. map
HashMap은 키(key)와 값(value)을 하나의 데이터로 저장하는 특징을 가진다.
Python의 dictionary와 동일하다.
이를 통하여 해싱(hashing)을 가능하게 하여 데이터를 검색하는데 뛰어난 성능을 보인다.

public class MapPrac {
    public static void main(String[] args) {
        //정의
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "apple");
        map.put(2, "pine apple");
        map.put(3, "apple mango");
        map.put(4, "cherry");
        map.put(5, "berry");
        System.out.println("map = " + map); //map = {1=apple, 2=pine apple, 3=apple mango, 4=cherry, 5=berry}
        System.out.println("map.get(0) = " + map.get(0)); //null -> index가 아닌 key를 넣어야 함
        System.out.println("map.get(1) = " + map.get(1)); //apple

        //삭제
        map.remove(2);
        System.out.println("map = " + map); //map = {1=apple, 3=apple mango, 4=cherry, 5=berry}

        //포함
        System.out.println("map.containsKey(2) = " + map.containsKey(2)); //flase
        System.out.println("map.containsValue(\"apple\") = " + map.containsValue("apple")); //true

        //전체 삭제
        map.clear();
        System.out.println("map = " + map); //map = {}

    }
}

  1. stack
    스택은 마지막에 저장한 데이터를 가장 먼저 꺼내는 자료구조 -> LIFO(Last In First Out)
    ex. 뒤로가기 버튼
public class StakPrac {
    public static void main(String[] args) {
        //정의
        Stack<Integer> stack = new Stack<>();
        stack.push(1);
        stack.push(3);
        stack.push(7);
        stack.push(5);
        System.out.println("stack = " + stack); // stack = [1, 3, 7, 5]

        //가장 위에 있는 데이터 꺼내기
        System.out.println(stack.peek());

        //가장 위에 있는 데이터 꺼내면서 삭제
        System.out.println(stack.pop());
        System.out.println(stack.size()); //3

        //포함
        System.out.println(stack.contains(1)); //true

        //stack.clear()와 같음
        while (!stack.empty()) {
            System.out.println(stack.pop()); // 7 3 1
        }

        System.out.println(stack); //[]
    }
}

  1. Queue
    큐는 처음에 저장한 데이터를 가장 먼저 꺼내게 되는 구조 -> FIFO(First In First Out)
    ex. 은행창구 줄서기
public class QueuePrac {
    public static void main(String[] args) {
        //정의
        Queue<Integer> queue = new LinkedList<>();
        queue.add(1);
        queue.add(8);
        queue.add(5);
        queue.add(3);
        System.out.println(queue); // [1, 8, 5, 3]

        //가장 앞에 있는 것을 출력
        System.out.println(queue.peek()); // 1
        
        //가장 앞에 있는 것을 출력하면서 삭제
        System.out.println(queue.poll()); // 1
        System.out.println(queue); // [8, 5, 3]
    }
}

6.ArrayDeque
실무에서는 단순히 Stack, Queue 클래스 대신에 ArrayDeque 많이 사용한다.
기본 Stack, Queue의 기능을 모두 포함하면서도 성능이 더 좋다.
큐는 한쪽에서만 값이 삽입되고 다른 한쪽에서만 값을 반환하지만 deque의 경우 양 끝에서 삽입과 반환이 가능하다.

public class ArrayDequePrac {
    public static void main(String[] args) {
        //정의
        ArrayDeque<Integer> arrayDeque = new ArrayDeque<>();
        //stack의 push()와 같음
        arrayDeque.addFirst(1);
        arrayDeque.addFirst(2);
        arrayDeque.addFirst(3);
        arrayDeque.addFirst(4);
        arrayDeque.addFirst(5);
        arrayDeque.addFirst(6);
        arrayDeque.push(7);
        System.out.println(arrayDeque); // [7, 6, 5, 4, 3, 2, 1]

        //queue의 add()와 같음
        arrayDeque.addLast(10);
        arrayDeque.addLast(11);
        arrayDeque.add(12);
        System.out.println(arrayDeque); // [7, 6, 5, 4, 3, 2, 1, 10, 11, 12]

        //addFirst와 비슷하지만 큐의 크기에 문제가 생기면 false를 리턴(addFirst는 exception)
        arrayDeque.offerFirst(20);
        System.out.println(arrayDeque); // [20, 7, 6, 5, 4, 3, 2, 1, 10, 11, 12]

        //addLast와 비슷하지만 큐의 크기에 문제가 생기면 false를 리턴(addLast는 exception)
        arrayDeque.offerLast(30);
        System.out.println(arrayDeque); // [20, 7, 6, 5, 4, 3, 2, 1, 10, 11, 12, 30]

        //return & remove
        System.out.println(arrayDeque.pollFirst()); // 20
        System.out.println(arrayDeque.pop()); // 7
        System.out.println(arrayDeque.poll()); // 6

        System.out.println(arrayDeque.pollLast()); //30

        System.out.println(arrayDeque); // [5, 4, 3, 2, 1, 10, 11, 12]

        //return
        System.out.println(arrayDeque.peek()); // 5
        System.out.println(arrayDeque.peekFirst()); // 5

        System.out.println(arrayDeque.peekLast()); // 12

        //크기
        System.out.println(arrayDeque.size()); // 8
    }
}

profile
Hello World!!

0개의 댓글