List<T>
List<T> 클래스는 동적으로 생성되고 삭제되는 자료를 저장할 때 가장 빈번하게 사용된다. 배열과 달리 크기가 가변이고, 제네릭 컬렉션이기 때문에 T에 어떠한 자료형도 넣을 수 있는 리스트이다.
List<int> list = new List<int>();
List<T>는 제네릭 컬렉션이므로 System.Collections.Generic을 using 문으로 포함시켜서 사용한다. 일반적으로 제네릭 컬렉션이 성능이 좋기 때문에 ArrayList를 쓸 경우가 있을 때에는 대신 List<T>를 사용하는 것이 권장된다. 참고로 제네릭 컬렉션에는 LinkedList<T>도 있다. 이름뿐 아니라 사용법도 비슷해서 List<T>와 혼동되는데, LinkedList<T>는 이중 연결 리스트다.
ex)
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
List<int> a = new List<int>();
Random r = new Random();
PrintValues(a);
for(int i = 0; i < 10; i++)
{
a.Add(r.Next(100));
}
PrintValues(a);
a.Sort();
PrintValues(a);
a.RemoveAt(3);
PrintValues(a);
}
private static void PrintValues(List<int> a)
{
Console.WriteLine("Print Values in List<int>");
Console.WriteLine("Count = {0}", a.Count);
Console.WriteLine("Capacity = {0}", a.Capacity);
foreach (var temp in a)
{
Console.Write(" {0}", temp);
}
Console.WriteLine();
}
}
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
List<int> aList = new List<int>();
Console.WriteLine("Capa : {0}", aList.Capacity);
aList.Add(100);
Console.WriteLine("Capa : {0}", aList.Capacity);
aList.Add(100);
Console.WriteLine("Capa : {0}", aList.Capacity);
aList.Add(100);
Console.WriteLine("Capa : {0}", aList.Capacity);
aList.Add(100);
Console.WriteLine("Capa : {0}", aList.Capacity);
Console.WriteLine("---------------------------");
aList.Add(100);
Console.WriteLine("Capa : {0}", aList.Capacity);
aList.Add(100);
Console.WriteLine("Capa : {0}", aList.Capacity);
}
}
'스마트팩토리 > C#' 카테고리의 다른 글
34. C# 파일 입출력 (0) | 2020.08.25 |
---|---|
33. IComparable 인터페이스 (0) | 2020.08.21 |
31. 숫자야구 만들기 (0) | 2020.08.20 |
30. Random 클래스 (0) | 2020.08.20 |
29. 익명타입(Anonymous Type) (0) | 2020.08.19 |