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

C# ArrayList 클래스란? 주요 메서드 15가지와 Sort() 정렬 예제

C# ArrayList 클래스란 무엇인가?

ArrayList 클래스는 각 요소를 개별적으로 인덱싱할 수 있는 객체의 순차적 컬렉션을 나타냅니다. 크기가 고정된 일반 배열과 달리 동적으로 요소를 추가하거나 제거할 수 있어, 실질적으로 배열의 유연한 대안으로 활용됩니다.

ArrayList 클래스의 주요 메서드

ArrayList 클래스에서 자주 사용되는 핵심 메서드를 아래 표로 정리했습니다.

번호메서드 및 설명
1public virtual int Add(object value);
ArrayList의 맨 끝에 객체를 추가하고, 해당 객체가 위치한 인덱스를 반환합니다.
2public virtual void AddRange(ICollection c);
ICollection의 모든 요소를 ArrayList의 맨 끝에 한꺼번에 추가합니다.
3public virtual void Clear();
ArrayList에서 모든 요소를 제거합니다.
4public virtual bool Contains(object item);
특정 요소가 ArrayList에 포함되어 있는지 여부를 확인합니다.
5public virtual ArrayList GetRange(int index, int count);
원본 ArrayList의 일부 요소로 구성된 새로운 ArrayList를 반환합니다.
6public virtual int IndexOf(object);
ArrayList 전체 또는 일부 구간에서 값이 처음 나타나는 위치(0부터 시작하는 인덱스)를 반환합니다.
7public virtual void Insert(int index, object value);
지정된 인덱스 위치에 요소 하나를 삽입합니다.
8public virtual void InsertRange(int index, ICollection c);
지정된 인덱스 위치에 컬렉션의 요소들을 삽입합니다.
9public virtual void Remove(object obj);
특정 객체가 처음으로 나타나는 항목을 ArrayList에서 제거합니다.
10public virtual void RemoveAt(int index);
지정된 인덱스에 있는 요소를 제거합니다.
11public virtual void RemoveRange(int index, int count);
지정된 위치부터 일정 범위의 요소들을 제거합니다.
12public virtual void Reverse();
ArrayList 내 요소들의 순서를 역순으로 뒤집습니다.
13public virtual void SetRange(int index, ICollection c);
컬렉션의 요소들을 ArrayList의 지정된 범위 위에 덮어써 복사합니다.
14public virtual void Sort();
ArrayList의 요소들을 정렬합니다.
15public virtual void TrimToSize();
ArrayList의 용량을 실제 요소 개수에 맞게 조정하여 메모리를 절약합니다.

Sort() 메서드로 ArrayList 정렬하기

C#에서 ArrayList를 오름차순으로 정렬하려면 Sort() 메서드를 사용하면 됩니다. 먼저 다음과 같이 ArrayList에 값을 추가해 보겠습니다.

ArrayList arr = new ArrayList();
arr.Add(32);
arr.Add(12);
arr.Add(55);
arr.Add(8);
arr.Add(13);

그다음 Sort() 메서드를 호출하면 요소들이 자동으로 정렬됩니다.

arr.Sort();

전체 예제 코드

using System;
using System.Collections;

namespace Demo {
    class Program {

        static void Main(string[] args) {

            ArrayList arr = new ArrayList();

            arr.Add(89);
            arr.Add(34);
            arr.Add(77);
            arr.Add(90);

            Console.Write("List: ");
            foreach (int i in arr) {
                Console.Write(i + " ");
            }

            Console.WriteLine();
            Console.Write("Sorted List: ");
            arr.Sort();
            foreach (int i in arr) {
                Console.Write(i + " ");
            }
            Console.WriteLine();
            Console.ReadKey();
        }
    }
}

실행 결과

List: 89 34 77 90
Sorted List: 34 77 89 90

실행 결과를 보면 Sort() 호출 전에는 입력 순서대로 출력되지만, 호출 후에는 값이 오름차순으로 깔끔하게 정렬된 것을 확인할 수 있습니다. 이처럼 ArrayList는 동적 데이터 관리와 정렬 작업에 매우 유용하게 활용될 수 있습니다.