GetHashCode good practice?
Asked Answered
E

1

6

For a Delphi project (built with RAD Studio XE7), I want to create a dictionary of brushes. Each dictionary item contains a TMyBrush object as key, that describes the brush to retrieve, and a GDI+ brush as value.

The TMyBrush class contains 3 fields

  • An enumerated type to determine the kind of brush (solid, gradient, ...)
  • A TBrushInfo class that describes the brush content (color, wrap mode, ...)
  • A TRect that represents a clamp field

In my dictionary, I want to retrieve a brush based on his characteristics, and not on his instance. For example, I want to get a black solid brush from my dictionary by creating a local TMyBrush instance, configuring it to black solid, and getting the matching GDI+ value using the TryGetValue() function. For that, I created a TMyBrushComparer.

Writing the Equals() function isn't a problem for me. However I don't know what is the best practice to write the GetHashCode() function. I would tend 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 is not a very good practice, it is correct? So, what is the best practice to write a good GetHashCode() function for my TMyBrushComparer?

Regards

Eleaseeleatic answered 10/12, 2016 at 13:26 Comment(0)
D
5

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

Your definition of equality is that three of the fields are equal. Your hash function should match that definition. Hash each of the three fields, and combine the values, for instance using the approach outlined here: https://mcmap.net/q/30334/-what-is-the-best-algorithm-for-overriding-gethashcode

Two of your fields are value types. They are easy to hash to match value identity. The brush info field appears to be a reference type. So again you need to decide what form of identity you want (reference identity, value identity, or perhaps something else) and then implement matching equality test and hash.

Diwan answered 10/12, 2016 at 15:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.