posted by 방랑군 2012. 1. 16. 21:46

 Generic 형태의 컬렉션 구조를 사용하기

ArrayList

=

List<>

Hashtable

=

Dictionary<>

Queue

=

Queue<>

Stack

=

Stack<>

▼ Generic Collection

using System.Collections;

namespace ConsoleEx2
{
class Ex03_GenericCollection
{
static void Main(string[] args)
{
//ArrayList
ArrayList list1 = new ArrayList();
list1.Add(100); //int -> object
list1.Add(200); //업캐스팅
list1.Add(300); //박싱
int n1 = (int)list1[0]; // object -> int(다운,언박싱)

//ArrayList의 제네릭 버전 -> List<T>
//박싱, 언박싱이 일어나지 않는다
List<int> list2 = new List<int>(); //int[]
list2.Add(100); //int -> int
list2.Add(200);
list2.Add(300);

//언박싱이 일어나지 않는다
int n2 = list2[0];//int -> int

//아래와 같은 상황은 별로 권장x, 하나의 박스엔 같은 자료형의 집합만..
//제네릭 컬렉션에선 서로 다른 자료형을 저장할 순없다
//단지 박싱, 언박싱이 안일어난다는 차이밖에 없음
// 형변환이 일어나면 예상치 못한 에러 발생가능성이 높다!
list1.Add("홍길동");//x


//HashTable
Hashtable ht1 = new Hashtable();
ht1.Add("국어", 100);
ht1.Add("영어", 90);
ht1.Add("수학", 85);
int jumsu1 = (int)ht1["영어"];

//HashTable의 제네릭버전 -> Dictionary
//<키의 자료형, 값의 자료형>
Dictionary<string, int> ht2 = new Dictionary<string,int>();

//박싱, 언박싱 없음
ht2.Add("국어", 100);
ht2.Add("영어", 90);
ht2.Add("수학", 85);
int jumsu2 = ht2["영어"];


//Queue 제네릭
Queue<int> queue = new Queue<int>();
queue.Enqueue(100);
Console.WriteLine(queue.Dequeue() +100);

//Stack 제네릭
Stack<int> stack = new Stack<int>();
stack.Push(200);
Console.WriteLine(stack.Pop() + 100);

}
}
}

'강좌 > C#' 카테고리의 다른 글

Cross-thread operation not valid  (0) 2012.01.17
Delegate  (0) 2012.01.17
Hashtable, HashSet<T>, Dictionary<TKey, TValue>  (0) 2012.01.16
DictionaryEntry 구조체  (0) 2012.01.16
[C#] internal, protected internal  (0) 2012.01.16