상세 컨텐츠

본문 제목

arrayList, List, Hashtable, Dictionary, Queue, Stack

C#

by MJ_119 2024. 6. 19. 17:57

본문

ArrayList : 

ArrayList arrayList = new ArrayList();

// Add() : 원소를 arrayList 맨 뒤에 추가
arrayList.Add(1);
arrayList.Add("가나다라");
arrayList.Add(9.989);

// Count : 원소의 갯수
print(arrayList.Count);

// Remove(원소의 내용) : 원소를 직접 지움
arrayList.Remove(1);
arrayList.Remove("가나다라");
arrayList.Remove(9.989);

// RemoveAt(index) : 원소의 인덱스를 참고해서 지움
arrayList.RemoveAt(0);
arrayList.RemoveAt(1);
arrayList.RemoveAt(2);

// RemoveRange(index, 몇개지울지) : 원소의 인덱스부터 int 값만큼 지움
arrayList.RemoveRange(0,3); // 인덱스 0부터 3개(0,1,2)를 지움

// 원소 수정하기( 인덱스 참조 )
arrayList[0] = 3;

// arrayList의 모든 값을 초기화
arrayList.Clear();

// Contains() : 특정 값이 있으면 True로 반환
arrayList.Contains("가나다라"); // True

// Insert(index, 값) : 인덱스 자리에 값을 삽입 ( Add와 달리 중간에도 추가 가능)
arrayList.Insert(1, 3.3);

 

List :

List<int> list = new list<int>();

// 자료형을 맞춰야함
list.Add("asdfasd"); => 위에 생성을 int로 했는데 문자열(string)을 추가하려고 해서 오류 발생
list.Add(3);

 

Hashtable

Hashtable hashTable = new Hashtable();

// 특정 값을 찾기위해 키값으로 접근.
hashTable.Add("만", 10000);
hashTable.Add("백만", 1000000);
hashTable.Add(50, "1억");



print(hashTable[0]); // 오류. 키값으로 접근해야함
print(hashTable["만"]); // 출력값 : 10000
print(hashTable[50]); // 출력값 : 1억

 

Dictionary

Dictionary<string, int> dictionary = new Dictionary<string, int>();

dictionary.Add(100,100); // 오류 발생. 지정한 자료형을 넣어야함.
dictionary.Add("가",100);

 

Queue : 예를들어 포션 제작 대기줄 ( 은행 대기줄 )

 

 - Enqueue : 삽입

 - Dequeue : 꺼냄

Queue // 선입선출, FIFO

Queue<int> queue = new Queue<int>();

queue.Enqueue(5);
queue.Enqueue(10);

print(queue.Dequeue()); // 5
print(queue.Dequeue()); // 10
print(queue.Dequeue()); // 에러

if (queue.Count != 0)
	print(queue.Dequeue());

 

Stack : 후입선출, LIFO

 

 - Push : 삽입

 - Pop : 꺼냄

예를들어 요리게임 설거지 하는데 기존의 접시 위에 쌓고, 닦아놓은 맨위의 접시에 담아서 요리 서빙.

Stack<int> stack = new Stack<int>();

stack.Push(1);
stack.Push(2);
stack.Push(3);

print(stack.Pop()); // 3
print(stack.Pop()); // 2
print(stack.Pop()); // 1

 

'C#' 카테고리의 다른 글

인터페이스(interface)  (0) 2024.06.21
프로퍼티(property)  (0) 2024.06.21
델리게이트, 이벤트  (0) 2024.06.20
구조체(Struct), 열거형(enum)  (0) 2024.06.19
C# 메서드 정의  (0) 2023.07.04

관련글 더보기