2
votes

If I implement a relationship Car <-> Owner in Delphi using a TDictionary, how should I implement the Equals and GetHashCode function of the IEqualityComparer? (GetHashCode returns an Integer which is used for hashing in TDictionary.)

For the TVehicle class, assume that it has a VIN (vehicle identification number).

How should I implement the hashcode for the VIN?

Update: in this example, object identity does not mean 'identity of the memory locations of two object pointers', but 'identity of two instances of the same object, based on a unique and invariable ("immutable") combination of its properties'.

So instead of searching a vehicle by its memory address in the map, I need the vehicle which has the id I am looking for.

Think of a database which contains the vehicle-owner data, loaded into the dictionary at application startup. Now if the user enters a VIN in an application form, how can the application find the vehicle in the dictionary? If the code creates a new instance using VehicleFactory.CreateVehicleFromDatabase(Edit1.Text); and search for this object in the dictionary, the default implementation of Equals will not find any entries in the map, because it looks for the memory address. To find the vehicle, Equals needs to compare the VIN.

So I have to create a custom IEqualityComparer. Implementing Equals is trivial. But what about GetHashCode? For a string property, I can not simply use the address of the string (see Berry Kelly in Are Delphi strings immutable? : "If you create the same string from two separate sections of code, they will not share the same backing store"), so a GetHashCode function for a string property needs a customized implementation.

I also found I found the question How do I hash a string with Delphi? - there is an example which contains a HashValue('Hello World')

3
The default comparer for strings doesn't compare addresses.David Heffernan
More or less the missing piece in the puzzle is a GetHashCode for strings. In Delphi 2009 and higher, all objects have a GetHashCode method. Strings are no objects, so I was hoping that there is a system function in newer versions of Delphi.mjn
Strings do have hash codes, it's not based on the address of the string but rather on its contents. Where did you get the idea that strings can't be hashed in Delphi?David Heffernan
default string hash looks like this: BobJenkinsHash(Value[1], Length(Value) * SizeOf(Value[1]), 0) where Value is a string. It's comparing data.David Heffernan
@David if this were an answer I would accept it winkmjn

3 Answers

3
votes

I'd throw the KISS principle at this one, if possible. If your actual key is the ID and not the vehicle itself, then why not use a TDictionary<string, TPerson> instead of TDictionary<TVehicle, TPerson>? Then you wouldn't have to worry about custom comparers.

3
votes

Being you advised about a smell in your design and other things, I'll respond your question as it is valid to create a object keyed dictionary and compare it based in anything different than the memory address of the key:

You can create a new comparer at TDictionary creation time.

For example:

type
  TVehicleOwner = class (TDictionary<TVehicle, TOwner>)
  end;

//other code here

procedure TForm2.Button1Click(Sender: TObject);
var
  VehOwner: TVehOwner;
begin
  VehOwner := TVehOwner.Create(TEqualityComparer<TVehicle>.Construct(
    //comparer
    function(const Left, Right: TVehicle): Boolean
    begin
      { Make a case insensitive comparison }
      Result := CompareText(Left.FID, Right.FID) = 0;
    end,
    //hasher
    function(const Value: TVehicle): Integer
    begin
      { Generate a hash code. }
      Result := TheHashAlgorythmOfYourChoice(Value.FID);
    end)
  );

  //more code here

This said, I think it is a flaw in your code if you have two instances representing the same object. If you have a TVehicle with the ID 'ABC' in memory, as for me, this should be the only instance of that vehicle and you have to provide some way to get this same instance for all of your code. That way, you can use the Dictionary class without writing a custom comparer, but more important, you know you're working all the time with the same object and your application state will be and appear consistent to anything in code, UI or other interfaces.

3
votes

You appear to have been misled into the belief that Delphi strings do not come with a default hash code implementation.

This is not the case. When you create a TDictionary with a string value as a key, the hash is calculated based on the contents of the string. If Value is a string variable then the code looks like this:

BobJenkinsHash(Value[1], Length(Value) * SizeOf(Value[1]), 0);

I think this answers the part of your question concerning string hashing.


The comments to the other answers, and the ones I have deleted were an interesting discussion on the design problem you are contemplating. I'm still sceptical of your belief that the right solution is to allow a many-to-one relationship between TVehicle instances and VIN.

You have confirmed that you must not have multiple TVehicle instances with the same VIN but differing data. It seems to me that the best way to achieve this is to ensure that you have a one-to-one relationship between TVehicle instances and VIN.

This one-to-one relationship is quite easy to achieve. You need to make the instantiation of TVehicle instances a function private to a factory class. This factory class holds a dictionary containing the existing vehicle instances, TDictionary<string,TVehicle>. If you need to get hold of a vehicle you ask the factory for it. It returns either an existing one that was located in its dictionary, or synthesises a new one.

There are no doubt a number of other ways to achieve this effect, but I would strongly urge you to consider an approach that results in only a single vehicle instance per VIN.