Generics Collections TStack (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example demonstrates the usage of the generic TStack class.

Code

var
  Stack: TStack<String>;
begin
  { Create a new stack. }
  Stack := TStack<String>.Create;

  { Push some items to 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. }
  writeln('Last pushed element is: "' + Stack.Peek + '".');

  { Extract the top element: "Erica". }
  Stack.Extract;

  { Reduce the capacity. }
  Stack.TrimExcess;

  { The remaining count of elements }
  writeln('The stack now contains ' + IntToStr(Stack.Count) + ' elements.');

  { Show the last pushed element by modifying the stack. }
  writeln('Last pushed element is: "' + Stack.Pop() + '".');

  { Clear the stack. }
  Stack.Clear;

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

Uses

See Also