C#에서 Add() 메서드를 사용하면 ArrayList의 맨 끝에 개체를 간단하게 추가할 수 있습니다. 이 메서드는 컬렉션의 마지막 위치에 지정된 요소를 삽입하고, 새로 추가된 개체의 인덱스를 정수형(int) 값으로 반환합니다. 또한 내부 용량(capacity)이 가득 차면 ArrayList가 자동으로 크기를 확장해 주기 때문에, 요소 개수를 미리 알 수 없는 상황에서도 유연하게 사용할 수 있습니다.
예제 1
다음 예제는 ArrayList에 여러 개의 문자열을 순서대로 추가한 후, 전체 요소를 출력하는 코드입니다.
using System;
using System.Collections;
public class Demo {
public static void Main(String[] args){
ArrayList list = new ArrayList();
list.Add("Tim");
list.Add("Katie");
list.Add("Amy");
list.Add("Carlos");
list.Add("Chris");
list.Add("Jason");
Console.WriteLine("Elements in ArrayList...");
foreach (string res in list){
Console.WriteLine(res);
}
}
}
출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Elements in ArrayList... Tim Katie Amy Carlos Chris Jason
예제 2
이번에는 두 개의 서로 다른 ArrayList를 생성하고 각각에 요소를 추가한 뒤, 두 컬렉션이 동일한지 비교해 보겠습니다.
using System;
using System.Collections;
public class Demo {
public static void Main(String[] args){
ArrayList list1 = new ArrayList();
list1.Add("A");
list1.Add("B");
list1.Add("C");
list1.Add("D");
list1.Add("E");
list1.Add("F");
list1.Add("G");
list1.Add("H");
list1.Add("I");
Console.WriteLine("Elements in ArrayList1...");
foreach (string res in list1){
Console.WriteLine(res);
}
ArrayList list2 = new ArrayList();
list2.Add("1");
list2.Add("2");
list2.Add("3");
list2.Add("4");
list2.Add("5");
list2.Add("6");
Console.WriteLine("Elements in ArrayList2...");
foreach (string res in list2){
Console.WriteLine(res);
}
Console.WriteLine("Is ArrayList1 equal to ArrayList2? = "+list1.Equals(list2));
}
}
출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Elements in ArrayList1... A B C D E F G H I Elements in ArrayList2... 1 2 3 4 5 6 Is ArrayList1 equal to ArrayList2? = False
핵심 정리
- Add() 메서드는 항상 ArrayList의 맨 끝에 새 개체를 추가합니다.
- 반환값은 새로 추가된 개체의 인덱스(0부터 시작)입니다.
- 두 ArrayList를 비교할 때는 Equals() 메서드를 사용하며, 담고 있는 요소가 다르면 위 예제처럼 False가 반환됩니다.