unit Main;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Generics.Collections;

type
  TForm3 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
    procedure StackChanged(Sender: TObject; const Item: String; Action: TCollectionNotification);

  public
    { Public declarations }
  end;

var
  Form3: TForm3;

implementation

{$R *.dfm}

// BeginExample: Generics_Collections_TStack
// Class: Generics.Collections.TStack
// Event: Generics.Collections.TStack.OnNotify
// Method: Generics.Collections.TStack.Push
// Method: Generics.Collections.TStack.Peek
// Method: Generics.Collections.TStack.Extract
// Method: Generics.Collections.TStack.Pop
// Method: Generics.Collections.TStack.TrimExcess
// Method: Generics.Collections.TStack.Clear
// Property: Generics.Collections.TStack.Count

// BeginCode
{
This example demonstrates the usage of the generic TStack class.
}
procedure TForm3.Button1Click(Sender: TObject);
var
  Stack: TStack<String>;
begin
  { Create a new stack }
  Stack := TStack<String>.Create();

  { Register a notification call-back }
  Stack.OnNotify := StackChanged;

  { Push some items up the stack }
  Stack.Push('John');
  Stack.Push('Mary');
  Stack.Push('Bob');
  Stack.Push('Anna');
  Stack.Push('Erica');

  { Show the last pushed element without modifying the stack }
  MessageDlg('Last pushed element is: "' + Stack.Peek() + '".', mtInformation, [mbOK], 0);

  { Extract the top element: "John" }
  Stack.Extract();

  { Reduce the capacity }
  Stack.TrimExcess();

  { The remaining count of elements }
  MessageDlg('The stack contains ' + IntToStr(Stack.Count) + ' elements.', mtInformation, [mbOK], 0);

  { Show the last pushed element by modifying the stack }
  MessageDlg('Last pushed element is: "' + Stack.Pop() + '".', mtInformation, [mbOK], 0);

  { Clear the stack }
  Stack.Clear();

  { Destroy the stack completely }
  Stack.Free;
end;

procedure TForm3.StackChanged(Sender: TObject; const Item: String; Action: TCollectionNotification);
begin
  { This method is called by the Stack everytime a change occurs }
  if Action = cnAdded then
     MessageDlg('Element added: ' + Item, mtInformation, [mbOK], 0)
  else if Action = cnRemoved then
     MessageDlg('Element removed: ' + Item, mtInformation, [mbOK], 0)
  else if Action = cnExtracted then
     MessageDlg('Element extracted: ' + Item, mtInformation, [mbOK], 0)
end;
// EndCode
// EndExample: Generics_Collections_TStack
end.
