Hash a double in Java

懵懂的女人 提交于 2019-12-05 13:31:15

问题


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


回答1:


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



回答2:


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"




回答3:


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.




回答4:


This one worked for me

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


来源:https://stackoverflow.com/questions/9650798/hash-a-double-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!