在下面的示例中,将创建多少个对象?并解释与此相关的逻辑?
class test {
public static void main(String args[]) {
// 1 Integer Object
Integer i=10;
// 1 Integer Object
Integer j=10;
// sum of Integer Object
Integer k=i+j;
}
}据我所知,它将创建2个对象。对于Integervalue1,它在内部转换为Integer.valueOf(10),然后调用Integer的valueof方法,这些方法在内部调用IntegerCache,并通过创建对象来获取对象并存储在缓存中。类似于j,因为它已经被缓存,它指向相同的对象,然后k对象将被创建。所以总共有2个。
但是有些人说,Integer值在-127到+128之间,我们将从缓存中获取对象。对于Integervalue1,它在内部转换为Integer.valueOf(10),然后调用Integer的i=10方法,这些方法在内部调用IntegerCache并通过缓存获取对象。类似于缓存中的j。和K值20也来自于高速缓存。因此对象将为零。
所以我不确定它是0还是2。
如果有人知道,请让我知道。
发布于 2014-06-11 17:50:38
0是正确的,所有这些整数都将从缓存中拉出。
如果您将其更改为new Integer(10),则它将创建一个新对象。
如果您更改了i、j和/或k,使它们不是缓存值,那么它将再次创建新对象。
实际上,事情要比这复杂得多。无论缓存是创建的、已填充的还是按需延迟填充的,都取决于JVM实现。但是,从您的代码的角度来看,这是不可能区分的,也没有什么不同。
发布于 2014-06-11 18:10:53
,但是有些人说,整数的值在-127到+128之间,我们将从缓存中获取对象。对于Integervalue1,它在内部转换为Integer.valueOf(10),然后调用Integer的i=10方法,这些方法在内部调用IntegerCache并通过缓存获取对象。类似于缓存中的j。和K值20也来自于高速缓存。因此对象将为零。
这是真的,它确实缓存了:参见ref :Integer valueOf(int i)
如果你进入源代码,你会发现:
/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
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);
}希望你现在得到了答案。
https://stackoverflow.com/questions/24159758
复制相似问题