Good Practice GetHashCode?

For a Delphi project (built using RAD Studio XE7), I want to create a brush dictionary. Each element of the dictionary contains a TMyBrush object as a key, which describes a brush to extract, and a GDI + brush as a value.

The TMyBrush class contains 3 fields

  • Enumerated type for determining the type of brush (solid, gradient, ...)
  • The TBrushInfo class that describes the contents of the brush (color, wrapper mode, ...)
  • A TRect representing a clamp field

In my dictionary, I want to get a brush based on its characteristics, and not on its example. For example, I want to get a black solid brush from my dictionary by creating a local instance of TMyBrush, setting it to black, and getting the corresponding GDI + value using the TryGetValue () function. For this, I created TMyBrushComparer.

Writing the Equals () function is not a problem for me. However, I do not know how best to write the GetHashCode () function. I would like to write a function like this:

function TMyBrushComparer.GetHashCode(const pValue: TMyBrush): Integer;
begin
    Result := BobJenkinsHash(pValue, SizeOf(TMyBrush), 0);
end;

however, I feel that this is not a good practice, is that right? So what is the best way to write a good GetHashCode () function for my TMyBrushComparer?

Hi

+4
source share
1 answer

The code in the question hashes the address of the object, not its value, and therefore is not consistent with your definition of equality.

, . - . , , : fooobar.com/questions/1250/...

- . , . . , ( , , , - ), .

+3

Source: https://habr.com/ru/post/1663400/


All Articles