假设我的对象状态中有一个private static Integer i = 0
。假设我通过某种方法将其推送,该方法将此 i
作为参数,如下所示:pushThroughMethod(i)
。
i
是否被复制到堆上并有资格进行垃圾回收?
最佳答案
Java 基本类型(int、long、float 等)而非其对象对应类型(Integer、Long、Float 等)按值传递。另外,对对象的引用是按值传递的。但对象本身是通过引用传递的。
因此,如果您使用对象 O 调用方法 x(),则:
O o = new O(); // Create an O on the heap, put a reference to it on the stack
x(o); // Pass a copy of the reference into x, the reference still points to O
X 内部:
void x(O o) {
// o is a separate reference, so if you do o = null; it does not chance the reference in the calling function.
// but the o itself is shared, so if you do o->doSomething() the calling function will be able to see the results of doSomething().
}
在您的示例中,当您调用 pushThroughMethod(i)
时,会创建对 i
的新引用,但它指向相同的 Integer
>.
i
只有在所有强引用都消失后才有资格进行垃圾回收。在这种情况下,即使当pushThroughMethod()删除它对i
的引用时,静态引用也将保留并阻止收集。
关于java - 通过方法推送对象时是否会创建对象的副本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21040409/