daveb
daveb

Reputation: 3535

Hash a double in Java

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

Upvotes: 18

Views: 26177

Answers (4)

user1599755
user1599755

Reputation: 149

This one worked for me

int h2 = new Double(area).hashCode();

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533550

The way Java does it is to convert the raw bit of a double into a long.

// from Double.
public static long doubleToLongBits(double value) {
    long result = doubleToRawLongBits(value);
    // Check for NaN based on values of bit fields, maximum
    // exponent and nonzero significand.
    if ( ((result & DoubleConsts.EXP_BIT_MASK) ==
          DoubleConsts.EXP_BIT_MASK) &&
         (result & DoubleConsts.SIGNIF_BIT_MASK) != 0L)
        result = 0x7ff8000000000000L;
    return result;
}

public int hashCode() {
    long bits = doubleToLongBits(value);
    return (int)(bits ^ (bits >>> 32));
}

Note: There many values of NaN (and two types) but Java treats them as all the same.

Upvotes: 2

krico
krico

Reputation: 5728

Depending on what you need this for, you could go with a very simple approach of just mod(ing) it.

 int hash(double d) {
   return d % 71; //use a prime number here
 }

If it is just for storing a few doubles in a hash, this should do it. If you want to spread the hash, just increase the "71"

Upvotes: 2

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340763

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();

Upvotes: 31

Related Questions