Matrix3f.hashCode() source

In tyhe following code :


    public int hashCode() {
        int hash = 37;
        hash = 37 * hash + Float.floatToIntBits(m00);
        hash = 37 * hash + Float.floatToIntBits(m01);
        hash = 37 * hash + Float.floatToIntBits(m02);

        hash = 37 * hash + Float.floatToIntBits(m10);
        hash = 37 * hash + Float.floatToIntBits(m11);
        hash = 37 * hash + Float.floatToIntBits(m12);

        hash = 37 * hash + Float.floatToIntBits(m20);
        hash = 37 * hash + Float.floatToIntBits(m21);
        hash = 37 * hash + Float.floatToIntBits(m22);

        return hash;
    }



.. the hash variable doesn't have to be initialized to 37. 0 is fine too.

Same thing for hashCode() in the classes Matrix4f, Vector2f, Vector3f, Quaternion, etc ...

Yes, that is right – any hash function will do. Multiplying by 37 isn't actually the best possible mixer, and there's no separate additive value either. But it does the job; any possible improvement is marginal at best.



Btw: Do you actually write code that puts matrices as keys in a hashtable? And would the marginal difference in hash separation matter at all?

jwatte said:

Yes, that is right -- any hash function will do. Multiplying by 37 isn't actually the best possible mixer, and there's no separate additive value either. But it does the job; any possible improvement is marginal at best.


Yes. But should I still post some marginal fixes or am I wasting my time and the time of the dev team?
In other words, should we post small contributions not?

jwatte said:
Btw: Do you actually write code that puts matrices as keys in a hashtable? And would the marginal difference in hash separation matter at all?


Sometime, programmers want to put the matrices in a Set<Matrix3f>, and the hashCode() is used there when we do any request, insertion or deletion on the set.

I don't understand what your "fix" fixes though. Do you have a test case to show that it causes a more even distribution?

Also, using a hashCode() for unique index is dangerous, as there's no guarantee that two different matrices don't hash to the same code.

jwatte said:

I don't understand what your "fix" fixes though. Do you have a test case to show that it causes a more even distribution?


No, but it saves the CPU time of 1 useless addition of the constant 37^2.

jwatte said:
Also, using a hashCode() for unique index is dangerous, as there's no guarantee that two different matrices don't hash to the same code.


You don't need 2 different matrices to generate different hashcodes.

Extract from the JDK's javadoc:
It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.