HashMap with String keys


#1

Hi.

When using the HashMap with the default hashing I get assertions because sometimes my String::hashCode() is negative.

Should I provide my own hash function/ my own derived HashMap / something else?

Thanks.


#2

Hmm, I think that’s probably my mistake… I think the DefaultHashFunctions class should look have this correction:

static int generateHash (const String& key, const int upperLimit) noexcept { return (int) (((uint32) key.hashCode()) % upperLimit); }


#3

Please change the (uint32) part to (uint64).
It’s not uncommon to have a hash function in 64-bit on a 64-bit processor (think of Java’s getHash(Obj obj) { return &obj; })


#4

The String::hashCode method is only 32-bit, and the hashes are 32-bit, so that wouldn’t help in this case.


#5

No, it’s not a hash’s size issue (I doubt anyone use more than 4G entries in a hash table).
It’s because:
a % b != (a & 0xFFFFFFFF) % b (so the current code is mathematically wrong)

edit: Forget my remark, I was not reading the previous code snippet correctly.


#6

I’m trying to use Uuid::toString as a hash key but it gets caught with a negative number each time. Is this related to the noted fix or maybe I shouldn’t be attempting to use stringified Uuids as keys?


#7

With the fixed code above, it can’t produce a negative number.


#8

Right of course. Should I admit I didn’t have the latest tip? Doh…