티스토리 뷰

https://docs.microsoft.com/ko-kr/dotnet/api/system.collections.generic.list-1?view=netcore-3.1

 

List Class (System.Collections.Generic)

인덱스에서 액세스할 수 있는 강력한 형식의 개체 목록을 나타냅니다.Represents a strongly typed list of objects that can be accessed by index. 목록을 검색, 정렬 및 조작하는 메서드를 제공합니다.Provides methods

docs.microsoft.com

 

1. 간혹 크기를 설정하지 않은 리스트에 Clear() 같은 코드를 사용해서 오류가 뜨는데, 애초에 선언할 때 크기를 정해주자.

 

    public List<int> i = new List<int>();

 


2. Capacity != Lenght

Lenght는 배열의 Size를 의미하지만 Capacity는 Size가 아닌 "내부 데이터 구조가 보유할 수 있는 전체 요소 수"라고" 라고 한다.

 

https://docs.microsoft.com/ko-kr/dotnet/api/system.collections.generic.list-1.capacity?view=netcore-3.1

 

List.Capacity Property (System.Collections.Generic)

크기를 조정하지 않고 내부 데이터 구조가 보유할 수 있는 전체 요소 수를 가져오거나 설정합니다.Gets or sets the total number of elements the internal data structure can hold without resizing.

docs.microsoft.com


3. List의 Count를 배열의 Lenght처럼 쓰는 실수를 간혹 해버린다...

 

public List<int> list = new List<int>();
    
for(int i = 0; i < list.Count; i++)
        {
            list.Remove(i);
            print("Count : " + list.Count.ToString() + "\n Capacity : " + list.Capacity.ToString());
        }

 

만약 상기한 코드에서 list가 10이라면 for문을 10번 반복하는 것이 아니라

for문 1회 차마다 요소가 하나씩 Remove 되어 for문 5회 차에서 i > list.Count 되어 for문이 끝난다.

원했던 for문 10회 반복은 실패하기 때문에 굳이 사용하고 싶다면

 

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


int listSize = list.Count;
for(int i = 0; i < listSize; i++)
        {
            print(list[i]);
        }

 

list.Count를 잠시 받아둘 임시 변수를 생성하여 사용한다.

 


일단 여기까지(20.07.09)

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함