본문 바로가기
Programming Language/C#

[C#] 컬렉션 (Collection)

by dbxxrud 2019. 10. 31.

컬렉션 - 같은 성격을 띠는 데이터의 모음을 담는 자료 구조.

 

 

Collections

 

  • ArrayList

  • Queue

  • Stack

  • Hashtable

 


 

ArrayList

 

ArrayList는 배열과 비슷한 컬렉션이다. 컬렉션의 요소에 접근할 때는 [] 연산자를 이용하고, 특정 위치에 있는 요소에 데이터를 임의로 할당할 수 도 있다. 한편, 배열과는 달리 컬렉션을 생성할 때 용량을 미리 지정할 필요가 없이 필요에 따라 자동으로 그 용량이 늘어나거나 줄어든다. 

가장 중요한 메서드는 Add(), RemoveAt(), Insert() 세 가지이다. 

 

Add()

 

이 메소드는 컬렉션의 가장 마지막에 있는 요소 뒤에 새 요소를 추가.

RemoveAt()

 

특정 인덱스에 있는 요소를 제거.

Insert()

 

원하는 위치에 새 요소를 삽입

 

ArrayList list = new ArrayList();

list.Add(10);

list.Add(20);

list.Add(30);

 

list.RemoveAt(1); // 20을 삭제!

 

list.Insert(1,25); // 25를 1번 인덱스에 삽입. 즉, 10과 30 사이에 25를 삽입

 

 

예제

 

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
using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
using System.IO;
 
namespace Practice2
{
    class MainApp
    {
        static void Main(string[] args)
        {
            ArrayList list = new ArrayList();
            for (var i = 0; i < 5++i)
                list.Add(i); //Add 메서드를 호출해서 요소 추가
 
            foreach (object obj in list)
                Write($"{obj} "); // foreach 문으로 리스트를 순회함.
            WriteLine();
 
            list.RemoveAt(2); // 삭제
 
            foreach (object obj in list)
                Write($"{obj} ");
            WriteLine();
 
            list.Insert(22); // 삽입
 
            foreach (object obj in list)
                Write($"{obj} ");
            WriteLine();
 
            list.Add("abc");
            list.Add("def");
 
            for (var i = 0; i < list.Count; ++i)
                Write($"{list[i]} ");
            WriteLine();
        }
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 


 

 

Queue

 

Queue는 대기열, 즉 기다리는 줄이라는 뜻이다. Queue 자료구조는 데이터나 작업을 차례대로 입력해뒀다가 입력된 순서대로 하나씩 꺼내 처리하기 위해 사용된다. 배열이나 리스트가 원하는 위치에 자유롭게 접근하는 반면에 Queue는 입력은 오직 뒤에서, 출력은 앞에서만 이루어진다.

 

Enqueue()

 

데이터의 입력

Dequeue()

 

데이터 꺼내기

 

Queue que = new Queue();

que.Enqueue(1);

que.Enqueue(2);

que.Enqueue(3);

que.Enqueue(4);

que.Enqueue(5);

 

 

데이터를 꺼낼 때 주의할 점은 Dequeue()를 실행하면 데이터를 자료 구조에서 실제로 꺼내게 된다는 점이다. 제일 앞에 있던 항목이 출력되고 나면 그 뒤에 있던 항목이 제일 앞으로 옮겨진다. 그래서 그다음에 Dequeue()를 실행하면 제일 앞으로 옮겨진 데이터가 나오고, 그 뒤에 있던 데이터가 다시 맨 앞으로 이동하게 된다.

 

 

 

예제

 

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
using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
using System.IO;
 
namespace Practice2
{
    class MainApp
    {
        static void Main(string[] args)
        {
            Queue queue = new Queue();
            queue.Enqueue(1);
            queue.Enqueue(2);
            queue.Enqueue(3);
            queue.Enqueue(4);
            queue.Enqueue(5);
 
            while (queue.Count > 0)
                WriteLine(queue.Dequeue());
        }
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 


 

 

Stack

 

Stack은 Queue와 반대로 먼저 들어온 데이터가 나중에 나가고, 나중에 들어온 데이터는 먼저 나가는 구조의 컬렉션이다.

 

 

 

 

 

Stack에 데이터를 넣을 때는 Push() 메서들 이용하고, 데이터를 꺼낼 때는 Pop() 메서드를 이용하면 된다. Push() 메서드는 데이터를 위에 "쌓고", Pop() 메서드는 제일 위에 쌓여 있는 데이터를 "꺼낸다". Pop()을 호출하여 데이터를 Stack에서 꺼내고 나면 그 데이터는 컬렉션에서 제거가 되고 그 아래에 있던 데이터가 제일 위로 올라간다. 그다음에 Pop()을 호출하면 방금 올라온 데이터를 꺼내게 된다. 

 

Stack stack = new Stack();

stack.Push(1); // 최상위 데이터는 1

stack.Push(2); // 최상위 데이터는 2

stack.Push(3); // 최상위 데이터는 3

 

int a = (int) stack.Pop(); // 최상위 데이터는 다시 2

 

 

예제

 

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
using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
using System.IO;
 
namespace Practice2
{
    class MainApp
    {
        static void Main(string[] args)
        {
            Stack stack = new Stack();
            stack.Push(1);
            stack.Push(2);
            stack.Push(3);
            stack.Push(4);
            stack.Push(5);
 
            while (stack.Count > 0)
                WriteLine(stack.Pop());
        }
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 


 

Hashtable

 

키 와 값의 쌍으로 이루어진 데이터를 다룰 때 사용한다. "book"을 키로, "책"을 값으로 입력하는 식이다. Hashtable은 탐색 속도가 빠르고, 사용하기도 편하다. 

 

Hashtable ht = new Hashtable();

ht ["book"] = "책";

ht ["cook"] = "요리사";

ht ["tweet"] = "지저귀다";

 

WriteLine(ht ["book"]);

WriteLine(ht ["cook"]);

WriteLine(ht ["tweet"]);

 

배열과 비슷하지만 배열이 데이터를 저장할 요소의 위치로 인덱스를 사용하는 반면에, Hashtable 컬렉션은 키 데이터를 그대로 사용한다. 또한 어떤 형식이든 키로 사용할 수 있다. int 형식도 float 형식도 또한 클래스도 말이다. Hashtable은 편의성뿐만 아니라 배열에서 인덱스를 이용해서 배열 요소에 접근하는 것에 준하는 탐색 속도를 자랑한다. 

 

ArrayList에서 원하는 데이터를 찾으려면 컬렉션을 정렬해서 이진 탐색을 수행하거나 순차적으로 리스트를 탐색해 나가지만, Hashtable은 키를 이용해서 단번에 데이터가 저장되어 있는 컬렉션 내의 주소를 계산해낸다. 이 작업을 해싱(Hashing)이라고 한다.

 

 

예제

 

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
using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
using System.IO;
 
namespace Practice2
{
    class MainApp
    {
        static void Main(string[] args)
        {
            Hashtable ht = new Hashtable();
            ht["하나"= "one";
            ht["둘"= "two";
            ht["셋"= "three";
            ht["넷"= "four";
            ht["다섯"= "five";
 
            WriteLine(ht["하나"]);
            WriteLine(ht["둘"]);
            WriteLine(ht["셋"]);
            WriteLine(ht["넷"]);
            WriteLine(ht["다섯"]);
        }
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 


 

 

컬렉션의 초기화 방법

 

ArrayList, Queue, Stack은 배열의 도움을 받아서 간단하게 초기화를 수행할 수 있다. 이들 컬렉션의 생성자를 호출할 때 매개 변수로 배열 객체를 넘기면 컬렉션 객체는 해당 배열을 바탕을 내부 데이터를 채운다.

 

 

int [] arr = {123, 456, 789};

ArrayList list = new ArrayList(arr); // 123, 456, 789

Stack stack = new Stack(arr); // 789, 456, 123

Queue queue = new Queue(arr); // 123, 456, 789

 

ArrayList는 배열의 도움 없이 직접 컬렉션 초기자를 이용해서 초기화하는 것이 가능하다.

 

ArrayList list2 = new ArrayList() {11, 22, 33};

 

하지만 Stack과 Queue는 컬렉션 초기자를 이용할 수 없다. 컬렉션 초기자는 IEnumerable 인터페이스와 Add() 메서드를 구현하는 컬렉션만 지원하는데, 두 컬렉션은 IEnumerable은 상속하지만 Add() 메서드를 구현하지 않고 있기 때문이다.

 

Hashtable을 초기화 할때는 딕셔너리 초기자를 이용한다. 딕셔너리 초기자는 컬렉션 초기자와 비슷하게 생겼다. 

 

 

Hashtable ht = new Hashtable()

{

   ["하나"] = 1,

   ["둘"] = 2,

   ["셋"] 3

};

 

또한 컬렉션 초기자를 사용할 수 있다. 

 

 

Hashtable ht2 = new Hashtable()

{

  {"하나, 1"},

  {"둘, 2"},

  {"셋, 3"}

};

 

 

예제

 

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
using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
using System.IO;
 
namespace Practice2
{
    class MainApp
    {
        static void Main(string[] args)
        {
            // 배열을 이용한 컬렉션 초기화
 
            int[] arr = { 123456789 };
 
            ArrayList list = new ArrayList(arr);
            foreach (var item in list)
                WriteLine($"ArrayList : {item}");
            WriteLine();
 
            Stack stack = new Stack(arr);
            foreach (var item in stack)
                WriteLine($"Stack : {item}");
            WriteLine();
 
            Queue queue = new Queue(arr);
            foreach (var item in queue)
                WriteLine($"Queue : {item}");
            WriteLine();
            ////////////////////////////////////
 
            // 컬렉션 초기자를 이용한 컬렉션 초기화
 
            ArrayList list2 = new ArrayList() { 112233 };
            foreach (var item in list2)
                WriteLine($"ArrayList2 : {item}");
            WriteLine();
        }
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

 

 

 

 

※ 혼자서 공부하며 정리하는 블로그 입니다.

잘못된 정보가 있다면 알려주세요 :)

오늘도 감사합니다.

 

 

참고서적 : 이것이 C#이다. 

'Programming Language > C#' 카테고리의 다른 글

[C#] 인덱서  (0) 2019.11.03
[C#] 추상 프로퍼티  (0) 2019.10.15
[C#] System.Array  (0) 2019.10.02
[C#] 인터페이스의 프로퍼티  (0) 2019.10.02
[C#] 무명 형식  (0) 2019.10.02