Queue 제네릭 클래스 (System.Collections.Generic)

보기 전환:
ScriptFree
.NET Framework 클래스 라이브러리
Queue 제네릭 클래스

참고: 이 클래스는 .NET Framework 버전 2.0에서 새로 추가되었습니다.

개체의 선입선출(FIFO) 컬렉션을 나타냅니다.

네임스페이스: System.Collections.Generic
어셈블리: System(system.dll)

구문

Visual Basic(선언)
<SerializableAttribute> _
<ComVisibleAttribute(False)> _
Public Class Queue(Of T)
	Implements IEnumerable(Of T), ICollection, _
	IEnumerable
Visual Basic(사용법)
Dim instance As Queue(Of T)

C#
[SerializableAttribute] 
[ComVisibleAttribute(false)] 
public class Queue<T> : IEnumerable<T>, ICollection, 
	IEnumerable
C++
[SerializableAttribute] 
[ComVisibleAttribute(false)] 
generic<typename T>
public ref class Queue : IEnumerable<T>, ICollection, 
	IEnumerable
J#
J#에서는 제네릭 형식 및 메서드를 사용할 수 있지만 새로 선언할 수는 없습니다.
JScript
JScript에서는 제네릭 형식 및 메서드를 지원하지 않습니다.

Type 매개 변수

T

큐에 있는 요소의 형식을 지정합니다.

설명

큐는 순차 프로세스에서 메시지를 받은 순서대로 저장하는 데 유용합니다. Queue에 저장되는 개체들은 한쪽 끝에서 삽입되고 다른쪽 끝에서 제거됩니다.

Queue의 용량은 Queue이 보유할 수 있는 요소의 수입니다. 이 구현에서는 Queue의 기본 초기 용량이 8이지만 이 기본값은 .NET Framework SDK의 다음 버전에서 변경될 수 있습니다. 요소가 Queue에 추가될 때 필요하면 내부 배열의 재할당을 통해 용량이 자동으로 증가됩니다. TrimExcess를 호출하여 용량을 줄일 수 있습니다.

Queue은 Null 참조(Visual Basic의 경우 Nothing)을 참조 형식에 대해 유효한 값으로 받아들이며 중복 요소를 허용합니다.

예제

다음 코드 예제에서는 Queue 제네릭 클래스의 몇 가지 메서드를 보여 줍니다. 이 코드 예제에서는 기본 용량으로 문자열의 큐를 만들고 Enqueue 메서드를 사용하여 문자열 5개를 큐에 대기시킵니다. 큐의 요소가 열거되지만 큐의 상태는 변경되지 않습니다. Dequeue 메서드를 사용하여 첫 번째 문자열을 큐에서 제거합니다. Peek 메서드를 사용하여 큐에서 다음 항목을 찾은 다음 Dequeue 메서드를 사용하여 해당 항목을 큐에서 제거합니다.

ToArray 메서드를 사용하여 배열을 만들고 큐 요소를 배열에 복사한 다음 IEnumerable을 사용하는 Queue 생성자에 배열을 전달하여 큐의 복사본을 만듭니다. 복사본의 요소가 표시됩니다.

큐 크기의 두 배인 배열이 만들어지고 CopyTo 메서드가 배열 중간에서 시작되는 배열 요소를 복사하는 데 사용됩니다. Queue 생성자를 다시 사용하여 시작 부분에 null 요소를 세 개 포함하는 큐의 두 번째 복사본을 만듭니다.

Contains 메서드를 사용하여 "four" 문자열이 큐의 첫 번째 복사본에 있음을 보여 준 다음 Clear 메서드를 사용하여 복사본을 지우고 Count 속성을 통해 큐가 비어 있음을 보여 줍니다.

Visual Basic
Imports System
Imports System.Collections.Generic

Module Example

    Sub Main

        Dim numbers As New Queue(Of String)
        numbers.Enqueue("one")
        numbers.Enqueue("two")
        numbers.Enqueue("three")
        numbers.Enqueue("four")
        numbers.Enqueue("five")

        ' A queue can be enumerated without disturbing its contents.
        For Each number As String In numbers
            Console.WriteLine(number)
        Next

        Console.WriteLine(vbLf & "Dequeuing '{0}'", numbers.Dequeue())
        Console.WriteLine("Peek at next item to dequeue: {0}", _
            numbers.Peek())    
        Console.WriteLine("Dequeuing '{0}'", numbers.Dequeue())

        ' Create a copy of the queue, using the ToArray method and the
        ' constructor that accepts an IEnumerable(Of T).
        Dim queueCopy As New Queue(Of String)(numbers.ToArray())

        Console.WriteLine(vbLf & "Contents of the first copy:")
        For Each number As String In queueCopy
            Console.WriteLine(number)
        Next
        
        ' Create an array twice the size of the queue, compensating
        ' for the fact that Visual Basic allocates an extra array 
        ' element. Copy the elements of the queue, starting at the
        ' middle of the array. 
        Dim array2((numbers.Count * 2) - 1) As String
        numbers.CopyTo(array2, numbers.Count)
        
        ' Create a second queue, using the constructor that accepts an
        ' IEnumerable(Of T).
        Dim queueCopy2 As New Queue(Of String)(array2)

        Console.WriteLine(vbLf & _
            "Contents of the second copy, with duplicates and nulls:")
        For Each number As String In queueCopy2
            Console.WriteLine(number)
        Next

        Console.WriteLine(vbLf & "queueCopy.Contains(""four"") = {0}", _
            queueCopy.Contains("four"))

        Console.WriteLine(vbLf & "queueCopy.Clear()")
        queueCopy.Clear()
        Console.WriteLine(vbLf & "queueCopy.Count = {0}", _
            queueCopy.Count)
    End Sub
End Module

' This code example produces the following output:
'
'one
'two
'three
'four
'five
'
'Dequeuing 'one'
'Peek at next item to dequeue: two
'
'Dequeuing 'two'
'
'Contents of the copy:
'three
'four
'five
'
'Contents of the second copy, with duplicates and nulls:
'
'
'
'three
'four
'five
'
'queueCopy.Contains("four") = True
'
'queueCopy.Clear()
'
'queueCopy.Count = 0

C#
using System;
using System.Collections.Generic;

class Example
{
    public static void Main()
    {
        Queue<string> numbers = new Queue<string>();
        numbers.Enqueue("one");
        numbers.Enqueue("two");
        numbers.Enqueue("three");
        numbers.Enqueue("four");
        numbers.Enqueue("five");

        // A queue can be enumerated without disturbing its contents.
        foreach( string number in numbers )
        {
            Console.WriteLine(number);
        }

        Console.WriteLine("\nDequeuing '{0}'", numbers.Dequeue());
        Console.WriteLine("Peek at next item to dequeue: {0}", 
            numbers.Peek());
        Console.WriteLine("Dequeuing '{0}'", numbers.Dequeue());

        // Create a copy of the queue, using the ToArray method and the
        // constructor that accepts an IEnumerable<T>.
        Queue<string> queueCopy = new Queue<string>(numbers.ToArray());

        Console.WriteLine("\nContents of the first copy:");
        foreach( string number in queueCopy )
        {
            Console.WriteLine(number);
        }
        
        // Create an array twice the size of the queue and copy the
        // elements of the queue, starting at the middle of the 
        // array. 
        string[] array2 = new string[numbers.Count * 2];
        numbers.CopyTo(array2, numbers.Count);
        
        // Create a second queue, using the constructor that accepts an
        // IEnumerable(Of T).
        Queue<string> queueCopy2 = new Queue<string>(array2);

        Console.WriteLine("\nContents of the second copy, with duplicates and nulls:");
        foreach( string number in queueCopy2 )
        {
            Console.WriteLine(number);
        }

        Console.WriteLine("\nqueueCopy.Contains(\"four\") = {0}", 
            queueCopy.Contains("four"));

        Console.WriteLine("\nqueueCopy.Clear()");
        queueCopy.Clear();
        Console.WriteLine("\nqueueCopy.Count = {0}", queueCopy.Count);
    }
}

/* This code example produces the following output:

one
two
three
four
five

Dequeuing 'one'
Peek at next item to dequeue: two
Dequeuing 'two'

Contents of the copy:
three
four
five

Contents of the second copy, with duplicates and nulls:



three
four
five

queueCopy.Contains("four") = True

queueCopy.Clear()

queueCopy.Count = 0
 */

상속 계층 구조

System.Object
  System.Collections.Generic.Queue
스레드로부터의 안전성

이 형식의 public static(Visual Basic의 경우 Shared) 멤버는 스레드로부터 안전합니다. 모든 인스턴스 멤버는 스레드로부터 안전하지 않을 수 있습니다.

Queue는 컬렉션이 수정되지 않으면 여러 개의 reader를 동시에 지원할 수 있습니다. 그렇다 하더라도 컬렉션을 열거하는 프로시저는 기본적으로 스레드로부터 안전하지 않습니다. 열거하는 동안 스레드로부터 안전하게 보호하려면 열거하는 동안 컬렉션을 잠글 수 있습니다. 여러 스레드에서 컬렉션에 액세스하여 읽고 쓸 수 있도록 허용하려면 사용자 지정 동기화를 구현해야 합니다.

플랫폼

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0에서 지원

.NET Compact Framework

2.0에서 지원
참고 항목