如何删除传递给Java方法的对象? [英] How can I delete an object passed into a Java method?

查看:183
本文介绍了如何删除传递给Java方法的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Java通过引用传递对象,因此当将对象作为参数传递给方法时,对方法内部参数进行本地处理的所有操作都将对实际对象进行.

I know that Java passes objects by reference, so when an object is passed as an argument into a method, anything that is done locally to the argument inside the method is done to the actual object.

void main(){
 String[] array1 = {"a","b","c"};
 someMethod(array1);
 print(array1.length);
}

void someMethod(String[] array){
 /..code here../
 array = null;
}

当我尝试打印array1.length时,我希望得到一个空指针异常,因为我的方法将其设置为null.但是,这没有发生.有这个原因吗?

I would expect to get a null pointer exception when trying to print array1.length because my method set it to null. However this is not happening. Is there a reason for this?

推荐答案

array只是该对象的另一个指针.因此,当您设置array = null;时,只是将指针设置为null.该对象仍然存在于堆中,并且仍由main()中的array1指向.

array within someMethod is just another pointer to the object. So when you're setting array = null;, you're just setting the pointer to null. The object still exists on the heap, and is still pointed to by array1 in main().

这篇关于如何删除传递给Java方法的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆