人们可以推荐快速简单的方法来组合两个对象的哈希码.我并不太担心碰撞,因为我有一个Hash Table可以有效地处理这个问题我只想要尽可能快地生成代码的东西.
阅读SO和网络似乎有几个主要候选人:
人们会推荐什么?为什么?
考虑以下记录:
TMyRecord = record
b: Boolean;
// 3 bytes of padding in here with default record alignment settings
i: Integer;
end;
Run Code Online (Sandbox Code Playgroud)
我希望实施IEqualityComparer<TMyRecord>
.为了做到这一点,我想打电话TEqualityComparer<TMyRecord>.Construct
.这需要提供一个TEqualityComparison<TMyRecord>
没有问题的我.
但是,Construct
还需要一个THasher<TMyRecord>
,我想知道实现它的规范方法.该函数需要具有以下形式:
function MyRecordHasher(const Value: TMyRecord): Integer;
begin
Result := ???
end;
Run Code Online (Sandbox Code Playgroud)
我希望我需要调用BobJenkinsHash
记录值的两个字段,然后将它们组合起来.这是正确的方法,我该如何组合它们?
我不使用的原因TEqualityComparison<TMyRecord>.Default
是它使用CompareMem
因为记录的填充而不正确.
我有以下几点class
:
TTest = class
private
FId: Integer;
FSecField: Integer;
FThirdField: Integer;
public
constructor Create(AId, ASecField, AThirdField: Integer);
// .....
end;
Run Code Online (Sandbox Code Playgroud)
然后我创建一个TObjectDictionary
这样的:
procedure TMainForm.btnTestClick(Sender: TObject);
var
TestDict: TObjectDictionary<TTest, string>;
Instance: TTest;
begin
TestDict := TObjectDictionary<TTest, string>.Create([doOwnsKeys]);
try
TestDict.Add(TTest.Create(1, 1, 1), '');
if TestDict.ContainsKey(TTest.Create(1, 1, 1)) then
ShowMessage('Match found')
else
ShowMessage('Match not found');
Instance := TTest.Create(1, 1, 1);
TestDict.Add(Instance, 'str');
if TestDict.ContainsKey(Instance) then
ShowMessage('Match found')
else
ShowMessage('Match not found');
finally
TestDict.Free;
end;
end;
Run Code Online (Sandbox Code Playgroud)
结果是:“找不到匹配项”、“找到匹配项”。我应该怎么做才能比较每个键的字段值而不是它们的地址?