I am using QT 4.8 and I notice that it has a QHash class which can be used as follows:
QHash<QString, int> hash;
hash["one"] = 1;
hash["three"] = 3;
hash["seven"] = 7;
hash.insert("twelve", 12);
If there is a hash collision, will it be handled correctly?
Yes, collisions will be handled. QHash is a standard implementation of the classic hash-table based container and wouldn’t be very reliable if it didn’t handle collisions correctly. Typically a hash-table based container will map keys not to a single entry in the list but to a “bucket” which may contain more than one entry where different keys map to the same hash value.
When fetching values, the hash value for the key leads to the correct bucket then the container will iterate through the entries in the bucket until it finds a match for the particular key you are looking for.
Although I could not find a specific reference in the documentation to the “correctness” of Qt’s implementation, this quote eludes to it. I can’t imagine it being otherwise.
A simple test will increase our confidence:
BadHashOjbect.h
main.cpp
The
BadHashObjectclass stores anintand its hash function will always return1so all objects added to aQHashusing this type as a key will result in a collision. The output from our test program shows that the collision is handled properly.