gpt4 book ai didi

java - 为什么 Integer 类的 Integer.valueOf 方法中使用了 assert?

转载 作者:IT老高 更新时间:2023-10-28 21:18:57 24 4
gpt4 key购买 nike

我正在研究 Integer 类实际上是如何使用缓存对象的,我在 Integer.valueOf 方法中找到了以下代码:

public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}

我的问题是:

最佳答案

断言的目的是建立不变量并记录实现。在这里,这个断言记录了当进入 valueOf 方法时 IntegerCache.high 值保证至少为 127 的事实。最好写一个断言而不是注释,因为当相应的命令行选项(-esa)处于 Activity 状态时,JVM也会检查断言。

通常这个断言永远不会抛出,因为 IntegerCache.high 是这样初始化的:

int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;

此代码保证该值至少为 127。因此,如果您修改 IntegerCache.high(使用反射和 setAccessible(true))或如果以后要修改 JDK 并在 IntegerCache.high 初始化代码中引入 bug。这就是存在断言的原因:捕捉错误。

关于java - 为什么 Integer 类的 Integer.valueOf 方法中使用了 assert?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33891156/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com