In my program, I handle a lot of lists of size n that all are permutations of [1,...,n]. My problem is that I put these permutations in HashMap
s and HashSet
s, and I need a good hashCode()
that avoids too many collisions.
All the solutions I have thought of lead to either a lot of collisions or an overflow. How can I write a good hashCode for permutations ?
Have you tried a 'rotating hash'? You could adjust the barrel rotate amount to see if it makes much difference to the hash distribution.
Please see link in karmakaze's answer. It shows a rotating shift in much neater code, and discusses the general details (and issues) with different basic hashes.
An overflow isn't bad. Just modulus it back in :-) Consider just a simple shift with an XOR and feed the "overflow" back into the stream?
Consider, for each element, with value i, where h is a long:
Happy coding.
you can take the first n primes and do
the overflow is a pretty good thing as you'll then be sure to have all bits engaged in the hash