仅将 ArrayList 作为值传递而不是引用 [英] Passing ArrayList as value only and not reference
问题描述
简单地说,我有一个带有 ArrayList 参数的方法.在该方法中,我修改 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
}
只需处理复制的列表.
这篇关于仅将 ArrayList 作为值传递而不是引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!