RAD Studio VCL Reference
ContentsIndex
PreviousUpNext
IEqualityComparer Interface

IEqualityComparer is the generic interface used to check the equality of two values.

Pascal
IEqualityComparer<T> = interface;
C++
template <T>
__interface IEqualityComparer;

IEqualityComparer is implemented by classes that need to support an equality comparison for two values of the same type. Generic collections require instances of classes that implement the IEqualityComparer interface in order to provide support for custom data types. For example, the Equals method is used by TList to compare whether a given value is present in the list. Aside from checking the equality of two values, IEqualityComparer also provides a GetHashCode method that is used to generate a hash code for any value. GetHashCode is extensively used in hash based map classes like TDictionary.

Note: We recommend that the TEqualityComparer class is used as base for custom equality comparers instead of directly implementing the IEqualityComparer interface.
 

Delphi Examples: 

 

{
This example demonstrates the usage of TDelegatedEqualityComparer and
anonymous methods in order to create a custom comparer.
The example assumes two memos and a button are present on the form.
}
procedure TForm3.Button1Click(Sender: TObject);
var
  Dictionary: TDictionary<String, Cardinal>;
  Comparer: IEqualityComparer<String>;
  I: Integer;
  AString: String;
begin
  { Create a new delegated comparer. We will use anonymous methods }
  Comparer := TDelegatedEqualityComparer<String>.Create(
    { TEqualityComparison<String> }
    function(const Left, Right: String): Boolean
    begin
      { Make a case insensitive comparison }
      Result := CompareText(Left, Right) = 0;
    end,
    { THasher<String> }
    function(const Value: String): Integer
    begin
      { Generate a hash code. Simply return the length of the string
        as its hash code }
      Result := Length(Value);
    end);

  { Create a new dictionary of string/cardinal }
  Dictionary := TDictionary<String, Cardinal>.Create(Comparer);

  { Populate the dictionary with strings in the memo }
  for I := 0 to InMemo.Lines.Count - 1 do
  begin
    { Get the list from the memo }
    AString := InMemo.Lines[I];

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

  { Copy the list with numbers to the memo }
  OutMemo.Clear;

  { Now populate the out memo with string and the number of times it was
    present in the initial memo}
  for AString in Dictionary.Keys do
    OutMemo.Lines.Add(AString + ':' + UIntToStr(Dictionary[AString]));

  { Free resources }
  Dictionary.Free();
end;

 

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!