본문 바로가기

프로그래밍/Java

Java_컬렉션 프레임워크

반응형

컬렉션 프레임 워크란 ?

자바에서 제공되는 자료구조(Data Structure) 구현 클래스들이다.
java.util 패키지에 구현되어 있다.
개발에 소요되는 시간을 절약하면서 최적화 된 알고리즘을 사용할 수 있다.

잘못 적은 부분) Map인터페이스에서 value는 중복을 허용하고, key만 중복을 허용하지 않음

Set 인터페이스

: 순서가 없고 중복을 허용하지 않고 유일한 값을 관리하는데 필요한 메서드가 선언된다.
아이디, 주민번호, 사번 등을 관리하는데 유용하다.
저장된 순서와 출력되는 순서가 다를 수 있다.

List 인터페이스

: 객체를 순서에 따라 저장하고 관리하는데 필요한 메서드가 선언된 인터페이스이다.
자료구조 리스트 (배열, 연결리스트)의 구현을 위한 인터페이스이다.
순서가 있고 중복을 허용한다.

Map 인터페이스

: 객체가 key-value의 쌍으로 이루어져있다.
key는 중복을 허용하지 않는다.

 

Set 인터페이스 예제 - 로또 랜덤번호 생성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package ch04;
 
import java.util.HashSet;
import java.util.Random;
 
public class SetMainTest2 {
 
    // main 함수
    public static void main(String[] args) {
 
        HashSet<Integer> numberSet = new HashSet<Integer>();
 
//        numberSet.add(getRandomNumber());
//        numberSet.add(getRandomNumber());
//        numberSet.add(getRandomNumber());
//        numberSet.add(getRandomNumber());
//        numberSet.add(getRandomNumber());
//        numberSet.add(getRandomNumber());
//        System.out.println(numberSet.size());
//        System.out.println(numberSet.toString());
 
        // 무조건 6개 사이즈 가지는 numberSet 구성하기
        int cnt = 0;
        while (numberSet.size() != 6) {
            cnt++;
            numberSet.add(getRandomNumber());
        }
        
        System.out.println(numberSet);
        System.out.println("반복 횟수 : " + cnt);
 
    } // end of main
 
    public static int getRandomNumber() {
        Random r = new Random();
        return r.nextInt(45+ 1;
    }
 
// end of class
cs

→ Set인터페이스는 순서가 없고 중복을 허용하지 않기 때문에 랜덤로또번호를 생성하기에 유리하다.
→ getRandomNumber() 메서드를 만들어 랜덤번호를 생성하는 기능을 만들고, HashSet을 생성하여 while문을 이용해 numberSet의 크기가 6일 때까지 numberSet에 랜덤 수를 저장(add)하고, cnt변수를 사용해 반복 횟수까지 출력하였다. (Set인터페이스는 인덱스가 없기 때문에 while문을 이용하여 출력한 점을 기억!)

<결과 화면>

 

List 인터페이스 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package ch04;
 
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
public class ArrayListMain {
 
    public static void main(String[] args) {
 
                // 자료구조 - 정수를 담을 수 있는 메모리 공간 선언
        ArrayList<Integer> list = new ArrayList<>();
        ArrayList<Student> members = new ArrayList<>();
 
        // 값 추가 방법
        list.add(3); // 인덱스 0번 - 3
        list.add(null); // 인덱스 1번 - null
        list.add(100); // 인덱스 2번 - 100
        list.add(120); // 인덱스 1번 - 20
        
        System.out.println(list.toString());
        System.out.println(list.size());
 
        // 값 삭제 방법
        list.remove(2); // 해당하는 요소에 접근해서 제거
        System.out.println(list.toString());
        System.out.println(list.size());
        // 매번 삭제하려면
        // list.clear(); // 전체 삭제
        System.out.println(list.toString());
        System.out.println(list.size());
 
        // 값을 화면에 출력하는 방법
        System.out.println("--------------------");
        System.out.println(list.get(2)); // 배열은 인덱스 연산처리, ArrayList는 .get()연산자를 호출
        System.out.println(list.get(0));
        // System.out.println(list.get(20));
 
        System.out.println("--------------------");
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
 
        System.out.println("--------------------");
        for (int abc상관없음 : list) {
            System.out.println("변수명 아무거나 됨" + abc상관없음);
        }
 
        System.out.println("--------------------");
        System.out.println(list.contains(70));
        System.out.println(list.contains(100));
 
        System.out.println(list.indexOf(100));
        System.out.println(list.indexOf(70)); 
        // 값이 없으면 -1을 반환한다.
        
        System.out.println("--------------------");
        Iterator<Integer> iter = list.iterator(); //반복자 녀석으로 형변환 해줌 iterator()
        while(iter.hasNext()) {
            System.out.println("값 확인 방법 : "+iter.next());
        }
        
    }
 
}
 
class Student {
 
}
cs

→ 우선 ArrayList를 생성해주고 값을 넣으려면 .add()를 사용해야 한다. List 인터페이스는 순서가 있기 때문에 .add() 한 순서부터 인덱스 0번 순으로 들어가게 되고, 인덱스를 지정해주고 싶다면 .add(인덱스, 값)과 같이 하면 된다.
→ list에 저장된 값을 출력하고 싶다면 toString()을 사용하여 출력할 수 있고, 값이 몇 개 들어있는지 알고 싶다면 size()를 사용하면 된다.

→ .remove()는 '()'안 인덱스에 접근하여 해당 값을 삭제하고, .clear()는 전체 삭제한다.
→ .get()은 '()'안 인덱스에 접근하여 해당 값을 출력한다.
→ .contains()는 요소 안에 있는지 없는지 판별하여 true또는 false로 반환한다.
→ .indexOf()는 요소 안에 값이 있으면 해당하는 인덱스 번호를 반환한다. (값이 없으면 -1을 반환)

→ Iterator는 컬렉션 프레임워크에 저장되어 있는 요소들을 읽어오는 방법 중 하나이다.
Iterator를 생성하고 .iterator()로 접근할 컬렉션에 접근하여 while문으로 hasNext()를 써주어 사용하여 출력하면 된다.

Map 인터페이스 예제

HashMap 과 HashTable이 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package ch04;
 
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Map.Entry;
 
public class MapMainTest {
 
    public static void main(String[] args) {
 
        Map map;
        Map<StringString> map1 = new HashMap<>(); // value - null값 허용
        Hashtable<StringString> map2 = new Hashtable<>(); // value - null값 허용 안 함
 
        // C R U D
        map1.put("A01""김포공항정문");
        map1.put("A02""김포공항후문");
        map1.put("A03""김포공항로비");
        map1.put("B01""인천공항정문");
        map1.put("B02""인천공항후문");
        map1.put("B03""인천공항로비");
        map1.put("C01"null);
 
        // map 자료구조의 전체 값 확인하기
        System.out.println(map1);
 
        // 값 꺼내는 방법 - key값을 통해서 값을 꺼낼 수 있다.
        System.out.println(map1.get("B03"));
        System.out.println(map1.get("C01"));
        System.out.println(map1.get("b01")); // 없는 key값을 요청하면 null이 반환된다.
 
        // 사이즈 확인
        System.out.println(map1.size());
        for (int i = 0; i < map1.size(); i++) {
            System.out.println(map1.get(i));
        }
 
        // map 원래 순서가 없지만 잠깐 응용을 하면 key값으로 for문 정도는 활용할 수 있다.
        HashMap<Integer, String> map3 = new HashMap<>();
        map3.put(0"A");
        map3.put(1"B");
        map3.put(2"C");
        map3.put(3"D");
        map3.put(4"E");
 
        for (int i = 0; i < map3.size(); i++) {
            System.out.println("value : " + map3.get(i));
        }
 
        // 삭제하는 방법
        map1.remove("C01");
        // map1.clear();
        System.out.println(map1.toString());
 
        // 자료구조는 반복문과 if문을 많이 활용한다.
        // map 계열을 for문과 활용하는 방법
        // map1<String, String>
 
//        Entry<String, String> entry1 = (Entry<String, String>)map1.entrySet();
 
        // key, value 한번에 꺼낼 수 있다. - 반복하면서
        for (Entry<StringString> entry2 : map1.entrySet()) {
            System.out.println("key : " + entry2.getKey());
            System.out.println("value : " + entry2.getValue());
            System.out.println("----------------");
        }
 
        System.out.println("=======================");
 
        System.out.println(map1.keySet().size());
        // map 값을 꺼낼 때 key값으로 접근 --> value
        // String str = map1.get("A01");
        for (String key : map1.keySet()) {
            System.out.println("key : " + key); // 반복 돌면서 key값 확인
            System.out.println("value : " + map1.get(key));
        }
 
    } //end of main
 
//end of class
cs

→ Map은 key와 value 구조로 데이터를 저장한다.

→ HashMap과 Hashtable의 차이점은 HashMap은 value를 null값을 허용하지만, Hashtable은 value를 null값을 허용하지 않는다. 

 

→ 값 저장 : .put("key", "value"); 

→ key값을 통해서 값을 꺼내는 방법 : .get("key");

→ size() 메서드로 길이를 확인할 수 있다. 

→ 데이터 삭제 : .remove("key") --> 해당 key값 삭제 / .clear() --> 전체 삭제

 

→ 반복문으로 entrySet() 메서드를 이용하여 Map에 저장되어 있는 전체를 출력할 수 있다. 

 

<결과 화면>

{A01=김포공항정문, A02=김포공항후문, B01=인천공항정문, A03=김포공항로비, B02=인천공항후문, B03=인천공항로비, C01=null}
인천공항로비
null
null
7
null
null
null
null
null
null
null
value : A
value : B
value : C
value : D
value : E
{A01=김포공항정문, A02=김포공항후문, B01=인천공항정문, A03=김포공항로비, B02=인천공항후문, B03=인천공항로비}
key : A01
value : 김포공항정문
----------------
key : A02
value : 김포공항후문
----------------
key : B01
value : 인천공항정문
----------------
key : A03
value : 김포공항로비
----------------
key : B02
value : 인천공항후문
----------------
key : B03
value : 인천공항로비
----------------
=======================
6
key : A01
value : 김포공항정문
key : A02
value : 김포공항후문
key : B01
value : 인천공항정문
key : A03
value : 김포공항로비
key : B02
value : 인천공항후문
key : B03
value : 인천공항로비

 

반응형

'프로그래밍 > Java' 카테고리의 다른 글

Java_소켓(Socket) 통신  (0) 2023.03.04
Java_Input/Output 스트림(Stream)  (0) 2023.03.02
Java_Thread  (0) 2023.02.17
Java_Swing 키보드 방향키로 이미지를 창 안에서만 움직이게 하기  (0) 2023.02.16
Java_예외처리  (0) 2023.02.16