相关疑难解决方法(0)

Why do == comparisons with Integer.valueOf(String) give different results for 127 and 128?

I have no idea why these lines of code return different values:

System.out.println(Integer.valueOf("127")==Integer.valueOf("127"));
System.out.println(Integer.valueOf("128")==Integer.valueOf("128"));
System.out.println(Integer.parseInt("128")==Integer.valueOf("128"));
Run Code Online (Sandbox Code Playgroud)

The output is:

true
false
true
Run Code Online (Sandbox Code Playgroud)

Why does the first one return true and the second one return false? Is there something different that I don't know between 127 and 128? (Of course I know that 127 < 128.)

Also, why does the third one return true?

I have read the answer of this question, but I still didn't get …

java comparison integer

179
推荐指数
5
解决办法
2万
查看次数

为什么Integer类缓存值在-128到127之间?

关于我之前的问题,为什么==与Integer.valueOf(String)的比较给出了127和128的不同结果?,我们知道Integer class有一个缓存存储-128和之间的值127.

只是想知道,为什么介于-128和127之间

Integer.valueOf()文档声明它" 缓存经常请求的值 ".但是-128,127经常要求真实的价值吗?我认为经常要求的价值观是非常主观的.
这背后有什么可能的原因吗?

从文档中还说:" ..并且可以缓存此范围之外的其他值. "
如何实现这一目标?

java caching

80
推荐指数
3
解决办法
2万
查看次数

标签 统计

java ×2

caching ×1

comparison ×1

integer ×1