Stack<T> クラス
定義
重要
一部の情報は、リリース前に大きく変更される可能性があるプレリリースされた製品に関するものです。 Microsoft は、ここに記載されている情報について、明示または黙示を問わず、一切保証しません。
同じ指定した型のインスタンスの可変サイズの先入れ先出し (LIFO) コレクションを表します。
generic <typename T>
public ref class Stack : System::Collections::Generic::IEnumerable<T>, System::Collections::Generic::IReadOnlyCollection<T>, System::Collections::ICollection
	generic <typename T>
public ref class Stack : System::Collections::Generic::IEnumerable<T>, System::Collections::ICollection
	public class Stack<T> : System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection
	[System.Runtime.InteropServices.ComVisible(false)]
[System.Serializable]
public class Stack<T> : System.Collections.Generic.IEnumerable<T>, System.Collections.ICollection
	[System.Runtime.InteropServices.ComVisible(false)]
[System.Serializable]
public class Stack<T> : System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection
	public class Stack<T> : System.Collections.Generic.IEnumerable<T>, System.Collections.ICollection
	type Stack<'T> = class
    interface seq<'T>
    interface IEnumerable
    interface IReadOnlyCollection<'T>
    interface ICollection
	[<System.Runtime.InteropServices.ComVisible(false)>]
[<System.Serializable>]
type Stack<'T> = class
    interface seq<'T>
    interface ICollection
    interface IEnumerable
	[<System.Runtime.InteropServices.ComVisible(false)>]
[<System.Serializable>]
type Stack<'T> = class
    interface seq<'T>
    interface IEnumerable
    interface ICollection
    interface IReadOnlyCollection<'T>
	type Stack<'T> = class
    interface seq<'T>
    interface ICollection
    interface IEnumerable
	Public Class Stack(Of T)
Implements ICollection, IEnumerable(Of T), IReadOnlyCollection(Of T)
	Public Class Stack(Of T)
Implements ICollection, IEnumerable(Of T)
    型パラメーター
- T
 
スタック内の要素の型を指定します。
- 継承
 - 
				Stack<T>
 
- 属性
 
- 実装
 
例
次のコード例は、Stack<T> ジェネリック クラスのいくつかのメソッドを示しています。 このコード例では、既定の容量を持つ文字列のスタックを作成し、Push メソッドを使用して 5 つの文字列をスタックにプッシュします。 スタックの要素は列挙され、スタックの状態は変更されません。 Pop メソッドは、スタックから最初の文字列をポップするために使用されます。 Peek メソッドを使用してスタック上の次の項目を確認し、Pop メソッドを使用してポップオフします。
ToArray メソッドは、配列を作成してスタック要素をコピーするために使用され、配列は IEnumerable<T>を受け取る Stack<T> コンストラクターに渡され、要素の順序が逆になったスタックのコピーが作成されます。 コピーの要素が表示されます。
スタックのサイズの 2 倍の配列が作成され、CopyTo メソッドを使用して、配列の中央から始まる配列要素をコピーします。 Stack<T> コンストラクターは、要素の順序を逆にしてスタックのコピーを作成するために再び使用されます。したがって、3 つの null 要素が最後にあります。
Contains メソッドは、文字列 "4" がスタックの最初のコピーにあることを示すために使用されます。その後、Clear メソッドはコピーをクリアし、Count プロパティはスタックが空であることを示します。
using System;
using System.Collections.Generic;
class Example
{
    public static void Main()
    {
        Stack<string> numbers = new Stack<string>();
        numbers.Push("one");
        numbers.Push("two");
        numbers.Push("three");
        numbers.Push("four");
        numbers.Push("five");
        // A stack can be enumerated without disturbing its contents.
        foreach( string number in numbers )
        {
            Console.WriteLine(number);
        }
        Console.WriteLine("\nPopping '{0}'", numbers.Pop());
        Console.WriteLine("Peek at next item to destack: {0}",
            numbers.Peek());
        Console.WriteLine("Popping '{0}'", numbers.Pop());
        // Create a copy of the stack, using the ToArray method and the
        // constructor that accepts an IEnumerable<T>.
        Stack<string> stack2 = new Stack<string>(numbers.ToArray());
        Console.WriteLine("\nContents of the first copy:");
        foreach( string number in stack2 )
        {
            Console.WriteLine(number);
        }
        // Create an array twice the size of the stack and copy the
        // elements of the stack, starting at the middle of the
        // array.
        string[] array2 = new string[numbers.Count * 2];
        numbers.CopyTo(array2, numbers.Count);
        // Create a second stack, using the constructor that accepts an
        // IEnumerable(Of T).
        Stack<string> stack3 = new Stack<string>(array2);
        Console.WriteLine("\nContents of the second copy, with duplicates and nulls:");
        foreach( string number in stack3 )
        {
            Console.WriteLine(number);
        }
        Console.WriteLine("\nstack2.Contains(\"four\") = {0}",
            stack2.Contains("four"));
        Console.WriteLine("\nstack2.Clear()");
        stack2.Clear();
        Console.WriteLine("\nstack2.Count = {0}", stack2.Count);
    }
}
/* This code example produces the following output:
five
four
three
two
one
Popping 'five'
Peek at next item to destack: four
Popping 'four'
Contents of the first copy:
one
two
three
Contents of the second copy, with duplicates and nulls:
one
two
three
stack2.Contains("four") = False
stack2.Clear()
stack2.Count = 0
 */
open System
open System.Collections.Generic
let numbers = Stack()
numbers.Push "one"
numbers.Push "two"
numbers.Push "three"
numbers.Push "four"
numbers.Push "five"
// A stack can be enumerated without disturbing its contents.
for number in numbers do
    printfn $"{number}"
printfn $"\nPopping '{numbers.Pop()}'"
printfn $"Peek at next item to destack: {numbers.Peek()}"
numbers.Peek() |> ignore
printfn $"Popping '{numbers.Pop()}'"
// Create a copy of the stack, using the ToArray method and the
// constructor that accepts an IEnumerable<T>.
let stack2 = numbers.ToArray() |> Stack
printfn "\nContents of the first copy:"
for number in stack2 do
    printfn $"{number}"
// Create an array twice the size of the stack and copy the
// elements of the stack, starting at the middle of the
// array.
let array2 = numbers.Count * 2 |> Array.zeroCreate
numbers.CopyTo(array2, numbers.Count)
// Create a second stack, using the constructor that accepts an
// IEnumerable(Of T).
let stack3 = Stack array2
printfn "\nContents of the second copy, with duplicates and nulls:"
for number in stack3 do
    printfn $"{number}"
printfn
    $"""
stack2.Contains "four" = {stack2.Contains "four"}"""
printfn "\nstack2.Clear()"
stack2.Clear()
printfn $"\nstack2.Count = {stack2.Count}"
// This code example produces the following output:
//       five
//       four
//       three
//       two
//       one
//
//       Popping 'five'
//       Peek at next item to destack: four
//       Popping 'four'
//
//       Contents of the first copy:
//       one
//       two
//       three
//
//       Contents of the second copy, with duplicates and nulls:
//       one
//       two
//       three
//
//       stack2.Contains("four") = False
//
//       stack2.Clear()
//
//       stack2.Count = 0
Imports System.Collections.Generic
Module Example
    Sub Main
        Dim numbers As New Stack(Of String)
        numbers.Push("one")
        numbers.Push("two")
        numbers.Push("three")
        numbers.Push("four")
        numbers.Push("five")
        ' A stack can be enumerated without disturbing its contents.
        For Each number As String In numbers
            Console.WriteLine(number)
        Next
        Console.WriteLine(vbLf & "Popping '{0}'", numbers.Pop())
        Console.WriteLine("Peek at next item to pop: {0}", _
            numbers.Peek())    
        Console.WriteLine("Popping '{0}'", numbers.Pop())
        ' Create another stack, using the ToArray method and the
        ' constructor that accepts an IEnumerable(Of T). Note that
        ' the order of items on the new stack is reversed.
        Dim stack2 As New Stack(Of String)(numbers.ToArray())
        Console.WriteLine(vbLf & "Contents of the first copy:")
        For Each number As String In stack2
            Console.WriteLine(number)
        Next
        
        ' Create an array twice the size of the stack, compensating
        ' for the fact that Visual Basic allocates an extra array 
        ' element. Copy the elements of the stack, starting at the
        ' middle of the array. 
        Dim array2((numbers.Count * 2) - 1) As String
        numbers.CopyTo(array2, numbers.Count)
        
        ' Create a second stack, using the constructor that accepts an
        ' IEnumerable(Of T). The elements are reversed, with the null
        ' elements appearing at the end of the stack when enumerated.
        Dim stack3 As New Stack(Of String)(array2)
        Console.WriteLine(vbLf & _
            "Contents of the second copy, with duplicates and nulls:")
        For Each number As String In stack3
            Console.WriteLine(number)
        Next
        Console.WriteLine(vbLf & "stack2.Contains(""four"") = {0}", _
            stack2.Contains("four"))
        Console.WriteLine(vbLf & "stack2.Clear()")
        stack2.Clear()
        Console.WriteLine(vbLf & "stack2.Count = {0}", _
            stack2.Count)
    End Sub
End Module
' This code example produces the following output:
'
'five
'four
'three
'two
'one
'
'Popping 'five'
'Peek at next item to pop: four
'Popping 'four'
'
'Contents of the first copy:
'one
'two
'three
'
'Contents of the second copy, with duplicates and nulls:
'one
'two
'three
'
'
'
'
'stack2.Contains("four") = False
'
'stack2.Clear()
'
'stack2.Count = 0
	注釈
Stack<T> は配列として実装されます。
スタックとキューは、情報のために一時ストレージが必要な場合に便利です。つまり、値を取得した後に要素を破棄したい場合です。 コレクションに格納されているのと同じ順序で情報にアクセスする必要がある場合は、Queue<T> を使用します。 情報に逆の順序でアクセスする必要がある場合は、System.Collections.Generic.Stack<T> を使用します。
複数のスレッドからコレクションに同時にアクセスする必要がある場合は、System.Collections.Concurrent.ConcurrentStack<T> 型と System.Collections.Concurrent.ConcurrentQueue<T> 型を使用します。
System.Collections.Generic.Stack<T> の一般的な用途は、他のプロシージャの呼び出し中に変数の状態を保持することです。
System.Collections.Generic.Stack<T> とその要素に対して、次の 3 つの主要な操作を実行できます。
Stack<T> の容量は、Stack<T> が保持できる要素の数です。 要素が Stack<T>に追加されると、内部配列を再割り当てすることで、必要に応じて容量が自動的に増加します。 TrimExcessを呼び出すことで容量を減らすことができます。
              Count がスタックの容量より小さい場合、Push は O(1) 操作です。 新しい要素に対応するために容量を増やす必要がある場合、Push は O(n) 操作になり、n が Countされます。 
              Pop は O(1) 操作です。
              Stack<T> は、参照型の有効な値として null を受け入れ、重複する要素を許可します。
コンストラクター
| Stack<T>() | 
		 空で、既定の初期容量を持つ Stack<T> クラスの新しいインスタンスを初期化します。  | 
        	
| Stack<T>(IEnumerable<T>) | 
		 指定したコレクションからコピーされた要素を含み、コピーされた要素の数に対応できる十分な容量を持つ、Stack<T> クラスの新しいインスタンスを初期化します。  | 
        	
| Stack<T>(Int32) | 
		 空で、指定した初期容量または既定の初期容量のいずれか大きい方を持つ、Stack<T> クラスの新しいインスタンスを初期化します。  | 
        	
プロパティ
| Capacity | 
		 内部データ構造がサイズを変更せずに保持できる要素の合計数を取得します。  | 
        	
| Count | 
		 Stack<T>に含まれる要素の数を取得します。  | 
        	
メソッド
| Clear() | 
		 Stack<T>からすべてのオブジェクトを削除します。  | 
        	
| Contains(T) | 
		 要素が Stack<T>内にあるかどうかを判断します。  | 
        	
| CopyTo(T[], Int32) | |
| EnsureCapacity(Int32) | 
		 このスタックの容量が、少なくとも指定された   | 
        	
| Equals(Object) | 
		 指定したオブジェクトが現在のオブジェクトと等しいかどうかを判断します。 (継承元 Object) | 
        	
| GetEnumerator() | 
		 Stack<T>の列挙子を返します。  | 
        	
| GetHashCode() | 
		 既定のハッシュ関数として機能します。 (継承元 Object) | 
        	
| GetType() | 
		 現在のインスタンスの Type を取得します。 (継承元 Object) | 
        	
| MemberwiseClone() | 
		 現在の Objectの簡易コピーを作成します。 (継承元 Object) | 
        	
| Peek() | 
		 Stack<T> の上部にあるオブジェクトを削除せずに返します。  | 
        	
| Pop() | 
		 Stack<T>の上部にあるオブジェクトを削除して返します。  | 
        	
| Push(T) | 
		 Stack<T>の上部にオブジェクトを挿入します。  | 
        	
| ToArray() | 
		 Stack<T> を新しい配列にコピーします。  | 
        	
| ToString() | 
		 現在のオブジェクトを表す文字列を返します。 (継承元 Object) | 
        	
| TrimExcess() | 
		 容量が現在の容量の 90% 未満の場合は、Stack<T>内の要素の実際の数に容量を設定します。  | 
        	
| TrimExcess(Int32) | 
		 Stack<T> オブジェクトの容量を、指定した数のエントリに設定します。  | 
        	
| TryPeek(T) | 
		 
              Stack<T>の先頭にオブジェクトがあるかどうかを示す値を返します。オブジェクトが存在する場合は、  | 
        	
| TryPop(T) | 
		 
              Stack<T>の先頭にオブジェクトがあるかどうかを示す値を返します。オブジェクトが存在する場合は、  | 
        	
明示的なインターフェイスの実装
| ICollection.CopyTo(Array, Int32) | 
		 特定の Array インデックスから始まる ICollection の要素を Arrayにコピーします。  | 
        	
| ICollection.IsSynchronized | 
		 ICollection へのアクセスが同期されているかどうかを示す値を取得します (スレッド セーフ)。  | 
        	
| ICollection.SyncRoot | 
		 ICollectionへのアクセスを同期するために使用できるオブジェクトを取得します。  | 
        	
| IEnumerable.GetEnumerator() | 
		 コレクションを反復処理する列挙子を返します。  | 
        	
| IEnumerable<T>.GetEnumerator() | 
		 コレクションを反復処理する列挙子を返します。  | 
        	
拡張メソッド
適用対象
スレッド セーフ
この型のパブリック静的 (Visual Basic のShared) メンバーはスレッド セーフです。 インスタンス メンバーがスレッド セーフであるとは限りません。
コレクションが変更されない限り、Stack<T> は複数のリーダーを同時にサポートできます。 それでも、コレクションを列挙することは本質的にスレッド セーフなプロシージャではありません。 列挙中のスレッド セーフを保証するために、列挙体全体の間にコレクションをロックできます。 読み取りと書き込みのためにコレクションに複数のスレッドからアクセスできるようにするには、独自の同期を実装する必要があります。