Collection Framework

Life is ninanino·2022년 9월 22일
0

JAVA

목록 보기
14/15

컬렉션즈 프레임워크라는 것은 다른 말로는 컨테이너라고도 부른다
값을 담는 그릇이라는 의미이다
그 값의 성격에 따라서 컨테이너의 성격이 조금씩 달라진다

ArrayList는 Collection-List에 속해있다.
List라는 성격으로 분류되고 있는 것이다.
List는 인터페이스이다. 그리고 List하위의 클래스들은 모두 List 인터페이스를 구현하기 때문에 모두 같은 API를 가지고 있다.

ArrayList

ArrayList는 크기를 지정하지 않기 때문에 얼마든지 많은 수의 값이 저장 가능하다
ArrayList는 배열과는 사용방법이 조금 다르다
배열의 경우 값의 개수를 구할때 .length를 사용했지만
ArrayList는 메소드 size를 사용한다. 또한 특정한 값을 가져올 때 배열은 [인덱스 번호]를 사용했지만 컬렉션은 .get(인덱스 번호)를 사용한다

ArrayList의 메소드 add입장에서는 인자로 어떤 형태의 값이 올지 알 수 없다
그렇게 때문에 모든 데이터 타입의 조상인 Object형식으로 데이터를 받고있다
get을 이용해서 꺼내도 Object의 데이터 타입을 가지고 있게 된다

ArrayList<String> a1 = new ArrayList<String>();

와 같은 형식으로 제네릭을 사용하면 ArrayList 내에서 사용할 데이터 타입을 인스턴스를 생성할 때 지정할 수 있기 때문데 데이터를 꺼낼때 String a1 = a1.get(i) 와 같이 형변환을 하지 않아도 된다

List와 set의 차이점

List와 Set의 차이점은 List는 중복을 허용하고, Set은 허용하지 않는다

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;

public class ListSet {
    public static void main(String[] args) {

        ArrayList<String> a1 =  new ArrayList<>();
        a1.add("one");
        a1.add("two");
        a1.add("one");
        Iterator ai = a1.iterator();
        while(ai.hasNext()) {
            System.out.println(ai.next());
        }

        // 중복을 허용하지 않는다
        HashSet<String> hs = new HashSet<String>();
        hs.add("one");
        hs.add("two");
        hs.add("one");
        Iterator hi = hs.iterator();
        System.out.println("\nhashset");
        while(hi.hasNext()){
            System.out.println(hi.next());
        }
    }
}

메소드 iterator는 인터페이서 Collection에 정의되어 있다.
따라서 Collection을 구현하고 있는 모든 컬렉션즈 프레임웍크는 이 메소드를 구현하고 있음을 보증한다
메소드 iterator의 호출 결과는 인터페이스 iterator을 구현한 객체를 리턴한다

  • hasNext
    반복할 데이터가 더 있으면 true, 더 이상 반복할 데이터가 없다면 false를 리턴한다
  • next
    hasNext가 true라는 것은 next가 리턴할 데이터가 존재한다는 의미다

Set은 중복을 허용하지 않고 순서가 없지만, List는 중복을 허용하고 저장되는 순서가 유지된다.

Set

Set은 한국어도 집합이라는 뜻이다
여기서 집합이란 수학의 집합과 같은 의미이다.
수학에서의 집합도 순서가 없고 중복되지 않는 특성이 있다
수학에서 집한은 교집함(intersect), 차집합(difference), 합집합(union)과 같은 연산을 할 수 있고 Set도 마찬가지다.

package 연습;

import java.util.HashSet;
import java.util.Iterator;

public class Set {
    public static void main(String[] args) {
        HashSet<Integer> A = new HashSet<Integer>();
        A.add(1);
        A.add(2);
        A.add(3);
        
        HashSet<Integer> B = new HashSet<Integer>();
        B.add(3);
        B.add(4);
        B.add(5);
        
        HashSet<Integer> C = new HashSet<Integer>();
        C.add(1);
        C.add(2);

        System.out.println(A.containsAll(B)); // false
        System.out.println(A.containsAll(C)); // true
        
        // A,addAll(B);
        // A.retainAll(B);
        // A.removeAll(B);

        Iterator hi = A.iterator();
        while(hi.hasNext()){
            System.out.println(hi.next());
        }
    }
}

부분집합(subset)

System.out.println(A.containsAll(B)); // false
System.out.println(A.containsAll(C)); // true

A = 1,2,3 / B = 3,4,5 / C = 1,2

A.containsAll(B) // false
B는 A의 부분집합이 아니다

A.containsAll(C) // true
C는 A의 부분 집합이다

합집합(union)

A,addAll(B); // A와 B의 합집합

교집합(intersect)

A.retainAll(B); // A와 B의 교집합

차집합(difference)

A.removeAll(B); // A에서 B를 뺀 차집합

Map

Map컬렉션은 key와 value의 쌍으로 값을 저장하는 컬렉션이다.

package 연습;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class MapDemo {
    public static void main(String[] args) {
        HashMap<String,Integer> a = new HashMap<String, Integer>();
        a.put("one",1);
        a.put("two",2);
        a.put("three",3);
        System.out.println(a.get("one"));
        System.out.println(a.get("two"));
        
        iteratorUsingForEach(a);
        iteratorUsingIterator(a);
    }

    private static void iteratorUsingIterator(HashMap map) {
        Set<Map.Entry<String,Integer>> entries = map.entrySet();
        for(Map.Entry<String,Integer> entry : entries){
            System.out.println(entry.getKey() + " : " +entry.getValue());
        }
    }

    private static void iteratorUsingForEach(HashMap map) {
        Set<Map.Entry<String,Integer>> entries = map.entrySet();
        Iterator<Map.Entry<String,Integer>> i = entries.iterator();
        while(i.hasNext()){
            Map.Entry<String,Integer> entry = i.next();
            System.out.println(entry.getKey()+ " : "+entry.getValue());
        }
    }
}

Map에서 데이터를 추가할 때 사용하는 API는 put이다. put의 첫번째 인자는 값의 key이고, 두번째 인자는 key에 대한 값이다. key를 이용해서 값을 가져올 수 있다.
a.get("one");

Map에 저장된 데이터를 열거 할 때는 어떻게 해야할까?

Set<Map.Entry<String,Integer>> entries = map.entrySet();
        for(Map.Entry<String,Integer> entry : entries){
            System.out.println(entry.getKey() + " : " +entry.getValue());

메소드 entrySet은 Map의 데이터를 담고있는 Set을 반환한다.
반환한 Set의 값이 사용할 데아터 타입은 인터페이스 Map.Entry인데 getKey,getValue 와 같은 API를 가지고 있어 Map의 key,value를 조회할 수 있다.

Set이 수학의 집합을 프로그래밍적으로 구현한 것이라면 map은 수학의 함수를 프로그래밍화 한 것이다.

데이터 타입의 교체

HashMap은 Map 인터페이스를 구현하기 때문의 변수 a의 데이터 타입으로 map을 사용할 수 있다.

Map<String,Integer> a = new HashMap<String,Integer>();

hashTable로 바꾸고 싶을땐 HashMap을 HashTable로 수정해서 사용하면 된다

정렬

컬렉션을 사용하는 이유 중의 하나는 정렬과 같은 데이터와 관련된 작업을 하기 위해서다.
메소드 sort는 List의 정렬을 수행한다

여기까지는 맛보기.
자료구조와 알고리즘으로 심화과정을 공부해야한다 ㅠㅠ

profile
백엔드 프로그래밍을 공부하고 있습니다. AWS, 클라우드 환경에 대해 관심이 많습니다.

0개의 댓글