![](/img/trans.png)
[英]Anyway to have two of the same keys, but different values in Java HashMap?
[英]Why can't HashMap have different NaN values as keys?
import java.util.*;
public class MyClass {
public static void main(String args[]) {
Map<Float, Integer> m = new HashMap<>();
m.put(Float.intBitsToFloat(0x7f800001), 1);
m.put(Float.intBitsToFloat(0x7f800002), 2);
System.out.println(m.size());
}
}
为什么上面的代码返回1
作为m
的大小? 0x7f800001
和0x7f800002
都是 NaN 浮点值,但由于NaN != NaN
根据定义,这不会导致冲突。
The behavior is similar to the documented handling of null
keys in the Java Hashmap, but I can't find anything that indicates that NaN
is handled as null
by HashMap.
Float.equals(Object)
记录为:
将此 object 与指定的 object 进行比较。 当且仅当参数不是 null 并且是
Float
object 时,结果才为真,该浮点数表示与此 object 表示的浮点数具有相同值的浮点数。 为此,当且仅当方法floatToIntBits(float)
在应用于每个浮点值时返回相同的int
值时,才认为两个浮点值相同。
现在听起来不同的 NaN 值应该被视为不相等,但floatToIntBits
文档包括(强调我的):
如果参数为 NaN,则结果为 0x7fc00000。
在所有情况下,结果都是 integer,当将其提供给
intBitsToFloat(int)
方法时,将生成与floatToIntBits
的参数相同的浮点值(除了所有 NaN 值都折叠为单个“规范”NaN 值) .
所以基本上, Float.equals
(和Float.hashCode
,它也使用floatToIntBits(float)
)将所有 NaN 值视为相等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.