闲来无事准备翻译JDK1.8部分源码玩玩。然后发现了一个以前没留意到的一个方法Float.isNaN(float v)
,用到的地方想必有很多,今天就说下我留意到它的地方吧。
源码如下:
/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and load factor.
*
* @param initialCapacity the initial capacity
* @param loadFactor the load factor
* @throws IllegalArgumentException if the initial capacity is negative
* or the load factor is nonpositive
*/
/**
* 带初始容量和负载因子的构造方法
*/
public HashMap(int initialCapacity, float loadFactor) {
// 初始容量小于0 抛出 IllegalArgumentException 异常
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
// 如果大于最大容量,则赋值为最大容量 (1 << 30)
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
// 负载因子小于等于0或者负载因子Not a number 抛出 IllegalArgumentException 异常
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " + loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
在对负载因子loadFactor
有效性进行判断的时候用到了Float.isNaN(loadFactor)
,
查看源码:
/**
* Returns {@code true} if the specified number is a
* Not-a-Number (NaN) value, {@code false} otherwise.
*
* @param v the value to be tested.
* @return {@code true} if the argument is NaN;
* {@code false} otherwise.
*/
public static boolean isNaN(float v) {
return (v != v);
}
excuse me? 什么鬼啊这是,我怎么发现我不太理解这波操作了?
注释大概是说:返回一个 Boolean 值,如果指定的数字是Not-a-Number (NaN)值,则返回{@code true},否则返回{@code false}
那什么情况下是NaN值呢?
度娘告诉我:
System.out.println(Float.isNaN(0.0f / 0.0f)); // true
System.out.println(Float.isNaN(0.0f)); // false
原来如此,涨了一波知识。