Dictionaries and Custom Classes
One benefit of the dictionary data type is the ability to accept almost any data type, including custom classes. In some cases however, the behavior of custom classes affects how they interact with dictionaries. This example shows how to overload two key functions for custom classes to make sure that dictionaries behave as expected.
Hash Equivalence
Dictionaries are hash maps, meaning that they convert keys into
uint64
scalar hash codes. Each hash code represents a unique key and
is used during lookup to quickly find the requested value. In MATLAB®, these scalars are generated using the keyHash
function, which uses input property information to generate a uint64
scalar. The keyMatch
function can be used to determine whether hashed keys are equivalent. For a dictionary to
function properly, when keyMatch(A,B)
is true, then
keyHash(A)
and keyHash(B)
must be equal. For most
data types, this relationship holds true without any extra steps. However, some custom
classes can have properties that you do not want to include as part of the comparison.
For example, create a class that is used to collect data and record the time that the
data was collected. This class has two properties dataValue
and
timestamp
.
classdef myDataClass properties dataValue double = 0 timestamp datetime = datetime end end
For the purposes of comparing data, only dataValue
is important.
However, keyHash
uses both properties when generating a hash
code.
Overload keyHash
and keyMatch
for Custom Classes
To make myDataClass
work as intended with dictionaries, overload
keyHash
and keyMatch
. Add
keyHash
and keyMatch
methods to
myDataClass
that use only the dataValue
property
to generate and compare hash values.
classdef myDataClass properties dataValue double = 0 timestamp datetime = datetime end methods function h = keyHash(obj) h = keyHash(obj.dataValue); end function tf = keyMatch(objA,objB) tf = keyMatch(objA.dataValue,objB.dataValue); end end end
See Also
dictionary
| keyHash
| keyMatch