我知道,如果你将盒装原始Integer与常量进行比较,例如:
Integer a = 4;
if (a < 5)
Run Code Online (Sandbox Code Playgroud)
a 将自动取消装箱,比较将起作用.
但是,当您比较两个盒装Integers并希望比较相等或小于/大于?时会发生什么?
Integer a = 4;
Integer b = 5;
if (a == b)
Run Code Online (Sandbox Code Playgroud)
以上代码是否会导致检查它们是否是同一个对象,还是会在这种情况下自动取消装箱?
关于什么:
Integer a = 4;
Integer b = 5;
if (a < b)
Run Code Online (Sandbox Code Playgroud)
?
可能重复:
奇怪的Java拳击
最近我看到了一个演示文稿,其中有以下Java代码示例:
Integer a = 1000, b = 1000;
System.out.println(a == b); // false
Integer c = 100, d = 100;
System.out.println(c == d); // true
Run Code Online (Sandbox Code Playgroud)
现在我有点困惑.我理解为什么在第一种情况下结果是"假" - 这是因为Integer是一个引用类型,而"a"和"b"的引用是不同的.
但为什么在第二种情况下结果是"真实的"?
我听说过一个观点,即JVM将对象的int值从-128缓存到127以进行某些优化.以这种方式,"c"和"d"的引用是相同的.
有人可以给我更多关于这种行为的信息吗?我想了解这种优化的目的.在什么情况下性能提高等等.参考这个问题的一些研究将是伟大的.
类Integer具有缓存,缓存Integer值.因此,如果我使用方法valueOf或收件箱,新值将不会被实例化,而是从缓存中获取.
我知道默认缓存大小是127因为VM设置而可以扩展.我的问题是:在这些设置中缓存大小的默认值有多大,我可以操纵这个值吗?这个值取决于我使用的是哪个VM(32位还是64位)?
我现在正在调整遗留代码,可能需要从int转换为Integer.
澄清:遵循我在Java源代码中找到的代码
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low));
}
high = h;
cache = …Run Code Online (Sandbox Code Playgroud)