传递的ArrayList的价值,而不是只引用 [英] Passing ArrayList as value only and not reference
问题描述
简单地说,我有一个ArrayList参数的方法。在该方法中我修改的ArrayList内容相关仅什么是该方法返回的目的。因此,我不希望在所有(即不作为引用传递)。
Simply put, I have a method with an ArrayList parameter. In the method I modify the contents of the ArrayList for purposes relevant only to what is returned by the method. Therefore, I do not want the ArrayList which is being passed as the parameter to be affected at all (i.e. not passed as a reference).
我已经试过一切都未能达到预期的效果。什么我需要做的,这样我只能在方法中使用ArrayList的副本,但又不希望它改变实际变量?
Everything I have tried has failed to achieve the desired effect. What do I need to do so that I can make use of a copy of the ArrayList within the method only, but not have it change the actual variable?
推荐答案
即使你有办法传递数组列表作为一个拷贝,而不是引用它本来只是一个浅拷贝。
Even if you had a way to pass the array list as a copy and not by reference it would have been only a shallow copy.
我会做这样的事情:
void foo(final ArrayList list) {
ArrayList listCopy = new ArrayList(list);
// Rest of the code
}
和刚才复制的名单上的工作。
And just work on the copied list.
这篇关于传递的ArrayList的价值,而不是只引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!