Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# ArrayList에서 지정된 인덱스의 요소 가져오기 및 설정하기

C#에서 ArrayList의 특정 인덱스에 있는 요소를 가져오거나 설정하려면 인덱서(indexer)를 사용하면 됩니다. 배열과 마찬가지로 대괄호([]) 안에 인덱스 번호를 지정하여 해당 위치의 요소에 접근할 수 있습니다.

예제 1: 인덱스로 요소 가져오기

다음 예제는 ArrayList에 여러 요소를 추가한 후, 인덱스 5에 해당하는 요소를 조회하는 방법을 보여줍니다.

using System;
using System.Collections;
public class Demo {
   public static void Main() {
      ArrayList arrList = new ArrayList();
      arrList.Add("Laptop");
      arrList.Add("Desktop");
      arrList.Add("Notebook");
      arrList.Add("Ultrabook");
      arrList.Add("Tablet");
      arrList.Add("Headphone");
      arrList.Add("Speaker");
      Console.WriteLine("ArrayList의 요소들...");
      foreach(string str in arrList) {
         Console.WriteLine(str);
      }
      Console.WriteLine("인덱스 5의 요소 = " + arrList[5]);
   }
}

출력 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

ArrayList의 요소들...
Laptop
Desktop
Notebook
Ultrabook
Tablet
Headphone
Speaker
인덱스 5의 요소 = Headphone

예제 2: 인덱스로 요소 설정(수정)하기

이번에는 같은 방식으로 특정 인덱스의 요소를 새로운 값으로 변경하는 예제입니다. 인덱서에 값을 할당하면 해당 위치의 기존 요소가 대체됩니다.

using System;
using System.Collections;
public class Demo {
   public static void Main() {
      ArrayList arrList = new ArrayList();
      arrList.Add("Laptop");
      arrList.Add("Desktop");
      arrList.Add("Notebook");
      arrList.Add("Ultrabook");
      arrList.Add("Tablet");
      arrList.Add("Headphone");
      arrList.Add("Speaker");
      Console.WriteLine("ArrayList의 요소들...");
      foreach(string str in arrList) {
         Console.WriteLine(str);
      }
      Console.WriteLine("인덱스 5의 요소 = " + arrList[5]);
      arrList[5] = "SSD";
      Console.WriteLine("인덱스 5의 요소 (변경 후) = " + arrList[5]);
   }
}

출력 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

ArrayList의 요소들...
Laptop
Desktop
Notebook
Ultrabook
Tablet
Headphone
Speaker
인덱스 5의 요소 = Headphone
인덱스 5의 요소 (변경 후) = SSD

참고 사항

ArrayList의 인덱스는 0부터 시작합니다. 따라서 위 예제에서 인덱스 5는 여섯 번째 요소인 "Headphone"을 가리킵니다. 또한 ArrayList는 형식에 안전하지 않은(non-generic) 컬렉션이므로, 최신 C# 코드에서는 형식 안전성이 보장되는 List<T> 사용을 권장합니다.