List
동영상 강의 링크
- 길이가 변하는 가변 배열
- 키워드:
Add, Insert, Contains, CopyTo, IndexOf, Reverse
- Count : 리스트 실제요소 갯수, Capacity: 리스트 배열의 총 크기
- 첫 Capacity 배열크기가 4였다면? 크기가 넘어서서 Add할경우 *2씩 함. (4,8,16,13,64,128...)
- 시간복잡도는 맨뒤에 데이터 추가시 O(1) , 맨뒤에 데이터 삭제시 O(1), 읽기 O(1)
- 검색은 모든 배열을 찾아야하므로 O(N)
- 추가,삭제는 O(N), 중간의 데이터를 삭제할경우 뒤의 데이터를 앞으로 당겨와야해서
코드예제
List<int> myInts = new List<int>();
myInts.Add(1);
myInts.Add(2);
myInts.Add(5);
Console.WriteLine(myInts.Count);
Console.WriteLine(myInts.Capacity);
myInts.Add(6);
myInts.Add(9);
Console.WriteLine(myInts.Count);
Console.WriteLine(myInts.Capacity);
Console.WriteLine("--구분선--");
myInts.Remove(1);
Console.WriteLine(myInts.IndexOf(9));
for (int i = 0; i < myInts.Count; i++)
{
Console.WriteLine(myInts[i]);
}
Console.WriteLine("----구분선2---");
2. List 를 실제 배열로 구현
class Ally
{
public string Name { get; set; }
public int PosX { get; set; }
private int PosY { get; set; }
public Ally()
{
Console.WriteLine("생성자 실행");
Name = "temp";
}
}
class Troop<T>
{
T[] army;
int count;
public int Capacity
{
get { return army.Length; }
}
public int Count
{
get { return count; }
private set
{
if (value < 0) value = 0;
count = value;
}
}
public T this[int index]
{
get
{
return army[index];
}
set
{
army[index] = value;
}
}
public Troop(int troopSize)
{
army = new T[troopSize];
}
public Troop()
{
army = new T[4];
count = 0;
}
public void RemoveAt(int index)
{
for (int i = index; i < count - 1; i++)
{
army[i] = army[i + 1];
}
count--;
}
public void Add(T unit)
{
if (army.Length <= count)
{
Array.Resize(ref army, army.Length * 2);
}
army[count] = unit;
count++;
}
}
class Program
{
static void Main(string[] args)
{
Troop<Ally> myTeam = new Troop<Ally>();
myTeam.Add(new Ally());
myTeam.Add(new Ally());
myTeam.Add(new Ally { Name = "Krnoya", PosX = 12 });
Console.WriteLine(myTeam[2].Name);
}
}
2차원 리스트
List<List<int>> twoDim = new List<List<int>>();
List<int> invenRowFirst = new List<int>();
List<int> invenRowSecond = new List<int>();
invenRowFirst.Add(10);
invenRowFirst.Add(20);
twoDim.Add(invenRowFirst);
twoDim[0].Add(1);