[Unity][C#] Collections

Yoo Hyung Joo ·2023년 10월 24일
0

ArrayList

정의
배열은 크기가 정해져있는 반면 ArrayList는 크기가 가변적으로 변합니다.

List vs ArrayList
C# List와 비슷한 역할을 하지만, List<>는 특정 타입만 담을 수 있고, ArrayList는 여러 타입을 전부 리스트에 넣어주는 것이 가능하다.
ex)

ArrayList arrayList = new ArrayList();
arrayList.Add("Hello World!");
arrayList.Add(10.0f);

for(int i = 0; i < 10; i++)
{
	arrayList.Add(i);
}
foreach(var a in arrayList)
{
	Console.WriteLine(a);
}

HashTable

정의
키와 요소에 따라 키를 넣으면 요소를 알려주는 자료구조이다.
탐색 시간복잡도 O(1)
ex)

Hashtable table = new Hashtable();

table.Add("사과", "apple");
table.Add("토마토", "tomato");
table["감자"] = "potato";

foreach (object obj in table.Keys)
{
	Console.WriteLine("{0}: {1}", obj, table[obj]);
}
              

예상출력
사과: apple
토마토: tomato
감자: potato

Queue

정의
Queue는 선입선출(First In First Out) 즉 먼저 들어간 요소가 먼저 나오는 것이다.
ex)

Queue queue = new Queue();

queue.Enqueue("one");
queue.Enqueue("two");
queue.Enqueue("three");
queue.Enqueue("four");

while(queue.Empty() == false)
{
	Console.WriteLine($"{queue.Dequeue()}");
}

예상 출력
one
two
three
four

Stack

정의
Stack은 Queue와 다르게 후입선출(Last In First Out) 즉 먼저 들어간 요소가 나중에 나오고 마지막에 들어간 요소가 먼저 나오게 된다.
ex)

Stack stack = new Stack();
stack.Push("1");
stack.Push("2");
stack.Push("3");
while(stack.Count > 0)
{
	Console.WriteLine($"{stack.Pop()]");
}

예상 출력
3
2
1

느낀점

Collection을 사용해본적이 Stack이나 Queue말고는 거의 없었다. 거의 항상 제네릭을 사용하다보니 Collection자체는 사용해 본 적이 없었는데 한 번 제네릭을 사용하지 않고 이 자료구조를 사용해 보는 것도 좋아보인다.

profile
성장을 멈추지 않는 개발자

0개의 댓글