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')
BobJenkinsHash(Value[1], Length(Value) * SizeOf(Value[1]), 0)
whereValue
is astring
. It's comparing data. – David Heffernan