Generics Defaults TCustomComparer (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example demonstrates the usage of TCustomComparer.

Code

type
  { Declare a custom string comparer descendant from TCustomComparer. }
  TCustomStringComparer = class(TCustomComparer<String>)
  public
    function Compare(const Left, Right: String): Integer; override;
    function Equals(const Left, Right: String): Boolean; override;
    function GetHashCode(const Value: String): Integer; override;
  end;

{ TCustomStringComparer }

function TCustomStringComparer.Compare(const Left, Right: String): Integer;
begin
  { Make a case-insensitive comparison. }
  Result := CompareText(Left, Right);
end;

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

function TCustomStringComparer.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 SortElements;
var
  List: TList<String>;
  I: Integer;
begin
  Randomize;
  { Create a new list of strings with the custom comparer. }
  List := TList<String>.Create(TCustomStringComparer.Create);

  { Populate the list with random numbers. }
  for I := 0 to 5 do
    List.Add(Random(5).ToString);

  { Sort the list }
  List.Sort;

  { Copy the list of numbers to the memo. }

  for I := 0 to List.Count - 1 do
    writeln(List[I]);

  { Free resources. }
  List.Free;
end;

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

  { Populate the dictionary with strings }
  for I := 0 to 5 do
  begin
    { Populate the list with random numbers. }
    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 string and the number of times the string was
    present in the dictionary.}
  for AString in Dictionary.Keys do
    writeln(AString + ':' + UIntToStr(Dictionary[AString]));

  { Free resources. }
  Dictionary.Free;
end;


begin
  { Call either one of the following procedures }
  SortElements;
  CountElements;
  readln;
end.

Uses