C#에서 ArrayList의 끝에 새로운 요소를 추가하려면 Add() 메서드와 AddRange() 메서드를 사용합니다. Add()는 단일 요소 하나를 리스트 맨 뒤에 추가하고, AddRange()는 배열이나 다른 컬렉션에 담긴 여러 요소를 한 번에 추가할 때 유용합니다.
예제 1 – Add()와 AddRange() 기본 사용법
using System;
using System.Collections;
public class Demo {
public static void Main(String[] args) {
ArrayList list = new ArrayList();
list.Add("Andy");
list.Add("Gary");
list.Add("Katie");
list.Add("Amy");
Console.WriteLine("ArrayList의 요소 목록");
foreach (string res in list) {
Console.WriteLine(res);
}
string[] strArr = { "John", "Jacob" };
list.AddRange(strArr);
Console.WriteLine("ArrayList의 요소 목록 (업데이트 후)");
foreach (String str in list) {
Console.WriteLine(str);
}
}
}
실행 결과
ArrayList의 요소 목록 Andy Gary Katie Amy ArrayList의 요소 목록 (업데이트 후) Andy Gary Katie Amy John Jacob
코드 설명
먼저 ArrayList 객체를 생성한 뒤 Add() 메서드로 네 개의 이름을 차례대로 추가했습니다. 이후 문자열 배열 strArr를 만들고 AddRange()를 호출하면, 배열에 담긴 모든 요소("John", "Jacob")가 기존 요소들의 바로 뒤에 순서대로 이어 붙여지는 것을 확인할 수 있습니다.
예제 2 – AddRange()를 여러 번 호출하기
AddRange()는 필요할 때마다 반복해서 호출할 수 있습니다. 호출할 때마다 전달된 컬렉션의 요소들이 ArrayList의 가장 뒤에 차례로 추가되며, 기존에 저장된 요소들은 그대로 유지됩니다.
using System;
using System.Collections;
public class Demo {
public static void Main(String[] args) {
ArrayList list = new ArrayList();
list.Add("Andy");
list.Add("Gary");
list.Add("Katie");
list.Add("Amy");
Console.WriteLine("ArrayList의 요소 목록");
foreach (string res in list) {
Console.WriteLine(res);
}
string[] strArr = { "John", "Jacob" };
list.AddRange(strArr);
Console.WriteLine("ArrayList의 요소 목록 (업데이트 후)");
foreach (String str in list) {
Console.WriteLine(str);
}
string[] strArr2 = { "Tim", "Tom", "David" };
list.AddRange(strArr2);
Console.WriteLine("ArrayList의 요소 목록 (업데이트 후)");
foreach (String str in list) {
Console.WriteLine(str);
}
}
}
실행 결과
ArrayList의 요소 목록 Andy Gary Katie Amy ArrayList의 요소 목록 (업데이트 후) Andy Gary Katie Amy John Jacob ArrayList의 요소 목록 (업데이트 후) Andy Gary Katie Amy John Jacob Tim Tom David
핵심 정리
- Add(object value): 단일 요소 하나를 ArrayList의 끝에 추가합니다.
- AddRange(ICollection c): 배열이나 컬렉션에 포함된 모든 요소를 ArrayList의 끝에 한꺼번에 추가합니다.
- 두 메서드 모두 항상 리스트의 마지막 위치에 요소를 추가하며, 기존 요소들의 인덱스에는 영향을 주지 않습니다.
- ArrayList는 내부적으로 크기가 자동으로 늘어나므로, 요소를 추가할 때 별도의 용량 관리가 필요하지 않습니다.