toHash

You’ll get to learn about the toHash function in this lesson.

Hash table indexes

Associative arrays are a hash table implementation. Hash table is a very fast data structure when it comes to searching elements in the table.

Note: Like most other things in software, this speed comes at a cost: Hash tables must keep elements in an unordered way, and they may be taking up space that is more than exactly necessary.

toHash function allows objects of a class type to be used as associative array keys. It does not affect the cases where the type is used as associative array values. If this function is defined, opEquals must be defined as well.

The high speed of hash tables comes from the fact that they first produce integer values for keys. These integers are called hash values. The hash values are then used for indexing into an internal array that is maintained by the table.

A benefit of this method is that any type that can produce unique integer values for its objects can be used as the key type of associative arrays. toHash is the function that returns the hash value for an object. Even Clock objects can be used as associative array key values:

Get hands-on with 1000+ tech skills courses.