Generics Collections TObjectStack (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example demonstrates the usage of the generic TObjectStack class.

Code

type
  { Declare a new object type. }
  TNewObject = class
  private
    FName: String;

  public
    constructor Create(const AName: String);
    destructor Destroy; override;
  end;

{ TNewObject }

constructor TNewObject.Create(const AName: String);
begin
  FName := AName;
end;

destructor TNewObject.Destroy;
begin
  { Show a message whenever an object is destroyed. }
  writeln('Object "' + FName + '" was destroyed!');
  inherited;
end;


var
  Stack: TObjectStack<TNewObject>;
begin
  { Create a new stack. }
  { The OwnsObjects property is set by default to true--the stack will free the owned objects automatically. }
  Stack := TObjectStack<TNewObject>.Create();

  { Push some items to the stack. }
  Stack.Push(TNewObject.Create('One'));
  Stack.Push(TNewObject.Create('Two'));
  Stack.Push(TNewObject.Create('Three'));

  { Pop an instance of the TNewObject class. The destructor
    is called for the owned objects, because you have set the OwnsObjects
    to true. }
  Stack.Pop;

  { Destroy the stack completely--more message boxes will be shown. }
  Stack.Free;
  readln;
end.

Uses