在 Java 中散列一个双精度值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9650798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hash a double in Java
提问by daveb
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.
我想知道如何在 Java 中散列双精度值?我已经散列其他原始数据和对象。我以为我可以使用哈希码方法?从我所见,这看起来相当复杂。我遇到了一些关于创建种子的事情。
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.
我想知道我尝试在 java 中散列数组列表、数组和其他对象是否有问题。我的一些类包含数组列表。
Many Thanks
非常感谢
采纳答案by Tomasz Nurkiewicz
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?
Double.hashCode()
复杂的?它基本上转换double
为 a long
(这里没有魔法,毕竟它们都只是内存中的 64 位值)并且计算long
哈希非常简单。本double
- >long
转换是通过做public static doubleToLongBits()
。这有什么复杂的?
Examples:
例子:
Double.valueOf(42.5).hashCode(); //better answer to everything
Long.valueOf(Double.doubleToLongBits(42.5)).hashCode();
回答by krico
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"
如果它只是为了在散列中存储一些双精度数,则应该这样做。如果你想传播散列,只需增加“71”
回答by Peter Lawrey
The way Java does it is to convert the raw bit of a double into a long.
Java 的做法是将 double 的原始位转换为 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.
注意: NaN 有很多值(和两种类型),但 Java 将它们视为完全相同。
回答by user1599755
This one worked for me
这个对我有用
int h2 = new Double(area).hashCode();