Generics Defaults TEqualityComparer (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example demonstrates the usage of TEqualityComparer and anonymous methods for creating a custom comparer.

Code

type
  TCustomEqualityComparer = class(TEqualityComparer<String>)
  public
    function Equals(const Left, Right: String): Boolean; override;
    function GetHashCode(const Value: String): Integer; override;
  end;

{ TCustomEqualityComparer }

function TCustomEqualityComparer.Equals(const Left, Right: String): Boolean;
begin
  { Make a case-insensitive comparison }
  Result := CompareText(Left, Right) = 0;
end;

function TCustomEqualityComparer.GetHashCode(const Value: String): Integer;
begin
  { Generate a hash code. Simply return the length of the string
    as its hash code. }
  Result := Length(Value);
end;

procedure NumberInstances(const AComparer: IEqualityComparer<String>);
var
  Dictionary: TDictionary<String, Cardinal>;
  I: Integer;
  AString: String;
begin
  Randomize;
  { Create a new dictionary of string/cardinal. }
  Dictionary := TDictionary<String, Cardinal>.Create(AComparer);

  { Populate the dictionary with random numbers as strings. }
  for I := 0 to 5 do
  begin
    { Get the list from the memo. }
    AString := Random(5).ToString;

    { If the string is already in the dictionary, increase its count
      by one. Otherwise add it to the dictionary with the default value of one.
    }
    if Dictionary.ContainsKey(AString) then
      Dictionary[AString] := Dictionary[AString] + 1
    else
      Dictionary.Add(AString, 1);
  end;

  { Now output the strings and the number of times each string was
    present in the dictionary. }
  for AString in Dictionary.Keys do
    writeln(AString + ':' + UIntToStr(Dictionary[AString]));

  { Free resources. }
  Dictionary.Free;
end;

procedure DefaultEqualityComparer;
begin
  { Use the equality comparer provided by default.}
  NumberInstances(TEqualityComparer<String>.Default);
end;

procedure CustomEqualityComparer;
begin
  { Use the custom generated equality comparer. }
  NumberInstances(TCustomEqualityComparer.Create);
end;

begin
  { Call either one of the following procedures }
  DefaultEqualityComparer;
  CustomEqualityComparer;
end.

Uses