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

C# Stack.ToArray() 메서드 – 스택을 새 배열로 손쉽게 복사하는 방법

C#의 Stack.ToArray() 메서드는 스택(Stack)에 저장된 모든 요소를 새로운 배열(Array)로 복사하는 데 사용됩니다. 이 메서드는 원본 스택을 변경하지 않으며, 스택의 요소들은 LIFO(후입선출) 순서 그대로 배열에 담기게 됩니다.

구문

Stack.ToArray() 메서드의 기본 구문은 다음과 같습니다.

public virtual object[] ToArray ();

이 메서드는 매개변수를 받지 않으며, 스택의 모든 요소를 포함하는 object[] 형식의 새 배열을 반환합니다.

예제 1: 문자열 스택을 배열로 복사하기

다음은 문자열 요소를 저장한 스택을 생성한 뒤, 동기화 처리를 거쳐 ToArray() 메서드로 새 배열에 복사하는 예제입니다.

using System;
using System.Collections;
public class Demo {
   public static void Main() {
      Stack stack = new Stack();
      stack.Push("Inspiron");
      stack.Push("Alienware");
      stack.Push("Projectors");
      stack.Push("Monitors");
      stack.Push("XPS");
      stack.Push("Laptop");
      stack.Push("Notebook");
      Console.WriteLine("Stack elements...");
      foreach(string val in stack) {
         Console.WriteLine(val);
      }
      Console.WriteLine("Count of elements = "+stack.Count);
      stack.Push("Ultrabook");
      stack.Push("Cameras");
      stack.Push("Keyboards");
      Console.WriteLine("\nStack elements...updated");
      foreach(string val in stack) {
         Console.WriteLine(val);
      }
      Console.WriteLine("\nCount of elements (updated) = "+stack.Count);
      Console.WriteLine("Is the Stack synchronized? = "+stack.IsSynchronized);
      Stack stack2 = Stack.Synchronized(stack);
      Console.WriteLine("Is the Stack synchronized? = "+stack2.IsSynchronized);
      Console.WriteLine("\nCopying the Stack to a new array...");
      Object[] objArr = stack2.ToArray();
      foreach(Object ob in objArr) {
         Console.WriteLine(ob);
      }
   }
}

출력 결과

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

Stack elements...
Notebook
Laptop
XPS
Monitors
Projectors
Alienware
Inspiron
Count of elements = 7
Stack elements...updated
Keyboards
Cameras
Ultrabook
Notebook
Laptop
XPS
Monitors
Projectors
Alienware
Inspiron
Count of elements (updated) = 10
Is the Stack synchronized? = False
Is the Stack synchronized? = True
Copying the Stack to a new array...
Keyboards
Cameras
Ultrabook
Notebook
Laptop
XPS
Monitors
Projectors
Alienware
Inspiron

실행 결과를 보면 스택의 특성상 마지막에 Push된 요소부터 역순으로 출력되는 것을 확인할 수 있습니다. 또한 Stack.Synchronized() 메서드로 동기화된 스택(IsSynchronized = True)에서도 ToArray()가 정상적으로 동작하여, 업데이트된 10개의 요소가 그대로 배열에 복사되었습니다.

예제 2: 정수 스택을 배열로 복사하기

이번에는 정수 값을 저장한 스택을 배열로 복사하고, 복사된 배열의 길이까지 함께 확인하는 예제입니다.

using System;
using System.Collections;
public class Demo {
   public static void Main() {
      Stack stack = new Stack();
      stack.Push(150);
      stack.Push(300);
      stack.Push(500);
      stack.Push(750);
      stack.Push(1000);
      stack.Push(1250);
      stack.Push(1500);
      stack.Push(2000);
      stack.Push(2500);
      Console.WriteLine("Stack elements...");
      foreach(int val in stack) {
         Console.WriteLine(val);
      }
      Console.WriteLine("Count of elements = "+stack.Count);
      stack.Push(3000);
      stack.Push(3500);
      stack.Push(4000);
      Console.WriteLine("\nStack elements...updated");
      foreach(int val in stack) {
         Console.WriteLine(val);
      }
      Console.WriteLine("\nCount of elements (updated) = "+stack.Count);
      Console.WriteLine("\nCopying the Stack to a new array...");
      Object[] objArr = stack.ToArray();
      foreach(Object ob in objArr) {
         Console.WriteLine(ob);
      }
      Console.WriteLine("\nCount of elements in array = "+objArr.Length);
   }
}

출력 결과

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

Stack elements...
2500
2000
1500
1250
1000
750
500
300
150
Count of elements = 9

Stack elements...updated
4000
3500
3000
2500
2000
1500
1250
1000
750
500
300
150
Count of elements (updated) = 12

Copying the Stack to a new array...
4000
3500
3000
2500
2000
1500
1250
1000
750
500
300
150
Count of elements in array = 12

복사된 배열의 길이(objArr.Length)가 스택의 요소 개수인 12와 정확히 일치하는 것을 확인할 수 있습니다. 이처럼 ToArray() 메서드는 스택의 전체 요소를 순서대로 배열에 복사해 주므로, 스택 데이터를 인덱스 기반으로 접근하거나 반복문 없이 한 번에 처리해야 할 때 매우 유용하게 활용할 수 있습니다.