Hash a double in Java

daveb picture daveb · Mar 10, 2012 · Viewed 21.1k times · Source

I was wondering how to hash a double in Java? I have hashed other primitive data and objects. I thought I could use the hashcode method? From what I have seen this looks quite complex. I came across something about creating a seed.

I was wondering any ideas on how to go about this. Hoping to put in with the rest of my hashcode for the class that has the double?

I was wondering if there are issues with me trying to hash arraylists, arrays and other objects in java. Some of my classes contain arraylists.

Many Thanks

Answer

Tomasz Nurkiewicz picture Tomasz Nurkiewicz · Mar 10, 2012

Double.hashCode() complex? It basically converts double into a long (no magic here, after all they both are simply 64-bit values in memory) and computing long hash is quite simple. The double -> long conversion is done via public static doubleToLongBits(). What is complex about this?

Examples:

Double.valueOf(42.5).hashCode();        //better answer to everything

Long.valueOf(Double.doubleToLongBits(42.5)).hashCode();