整数记忆
Memory of Integer
当我写的时候:
Integer i = 5;
Integer i = new Integer(5);
这两条线是否相等?
在内存中,类型 i
将在堆中分配,就像这两行中的方式一样?如果是,这一切是如何在内存中发生的?
Are these two lines equal?
没有
第一行同
Integer i = Integer.valueOf(5);
编译器将代码重写为autoboxing。
参考Javadoc for Integer.valueOf
:
If a new Integer instance is not required, this method should generally be used in preference to the constructor 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.
因此,Integer.valueOf(5) == Integer.valueOf(5)
(每次都返回同一个实例)而 new Integer(5) != new Integer(5)
(每次都创建一个新实例)。
但在所有情况下 - 与 Java 中的所有对象一样 - Integer 对象在堆上。
是正确的,应该接受。我可以添加更多想法和图表。
Integer
要删除的构造函数
请注意,所有原始包装器的构造函数 类 ( Integer
, Long
, Float
, etc.) are not only deprecated, as of Java 16 & 17 they are marked for eventual removal. See JEP 390: Warnings for Value-Based Classes.
因此,虽然这个问题在技术上很有趣,但实际上没有实际意义。
new
表示新
总结特纳的答案:new
表示新。通过 new
调用构造函数总是会导致实例化一个新对象。这意味着需要更多的内存来保存每个新对象。
Integer
个对象的缓存
另外两个途径,使用数字文字或调用Integer.valueOf
, may reuse an existing object cached by the JVM. Using a cache conserves memory。
这是调试器的修饰屏幕截图,显示了对这三种方法中的每一种方法调用 toString
的结果。我们可以看到 x
(数字字面量)和 y
(valueOf
工厂方法)都指向同一个对象。同时,z
(new
构造函数)指向不同的对象。
(添加 42
和 7
是为了产生戏剧效果,以强调缓存可能是一个包含许多对象的池。所示的实际代码不会生成这些对象。)
当我写的时候:
Integer i = 5;
Integer i = new Integer(5);
这两条线是否相等?
在内存中,类型 i
将在堆中分配,就像这两行中的方式一样?如果是,这一切是如何在内存中发生的?
Are these two lines equal?
没有
第一行同
Integer i = Integer.valueOf(5);
编译器将代码重写为autoboxing。
参考Javadoc for Integer.valueOf
:
If a new Integer instance is not required, this method should generally be used in preference to the constructor 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.
因此,Integer.valueOf(5) == Integer.valueOf(5)
(每次都返回同一个实例)而 new Integer(5) != new Integer(5)
(每次都创建一个新实例)。
但在所有情况下 - 与 Java 中的所有对象一样 - Integer 对象在堆上。
Integer
要删除的构造函数
请注意,所有原始包装器的构造函数 类 ( Integer
, Long
, Float
, etc.) are not only deprecated, as of Java 16 & 17 they are marked for eventual removal. See JEP 390: Warnings for Value-Based Classes.
因此,虽然这个问题在技术上很有趣,但实际上没有实际意义。
new
表示新
总结特纳的答案:new
表示新。通过 new
调用构造函数总是会导致实例化一个新对象。这意味着需要更多的内存来保存每个新对象。
Integer
个对象的缓存
另外两个途径,使用数字文字或调用Integer.valueOf
, may reuse an existing object cached by the JVM. Using a cache conserves memory。
这是调试器的修饰屏幕截图,显示了对这三种方法中的每一种方法调用 toString
的结果。我们可以看到 x
(数字字面量)和 y
(valueOf
工厂方法)都指向同一个对象。同时,z
(new
构造函数)指向不同的对象。
(添加 42
和 7
是为了产生戏剧效果,以强调缓存可能是一个包含许多对象的池。所示的实际代码不会生成这些对象。)