简体   繁体   English

使用ArrayList时的结果很奇怪 <ArrayList<String> &gt;在Java中

[英]Weird results when using an ArrayList<ArrayList<String>> in java

I'm getting weird problems in my android app and I think it may be linked to the behavior of the way the ArrayList works. 我在Android应用程序中遇到了奇怪的问题,我认为这可能与ArrayList工作方式的行为有关。 Check the following code and please tell me if I'm correct or doing something wrong: 检查以下代码,请告诉我是否正确或做错了什么:

ArrayList<ArrayList<String>> arr = new ArrayList<ArrayList<String>>();
ArrayList<String> tmp = new ArrayList<String>();
tmp.add("test");
arr.add(tmp);
tmp.clear();

After the last line the contents of arr[0] is emptied. 在最后一行之后,清空arr [0]的内容。 So does that mean that when adding one ArrayList to another it does it by reference? 那么这是否意味着在将一个ArrayList添加到另一个ArrayList时是否通过引用完成了?

So if I have the following method: 因此,如果我有以下方法:

void addArray(ArrayList<String> arr) {
 group.add(arr); // group is ArrayList<ArrayList<String>>;
};

I must change it to: 我必须将其更改为:

void addArray(ArrayList<String> arr) {
 ArrayList<String> tmp = new ArrayList<String>();
 tmp.addAll(arr);
 group.add(tmp); // group is ArrayList<ArrayList<String>>;
};

to make sure that if I clear the incoming array somewhere else that nothing happens to the group array? 确保如果我在其他地方清除传入数组,则组数组没有任何反应?

In Java there is no passing by value, every object is passed by reference. 在Java中,没有按值传递,每个对象都按引用传递。 So in your case arr[0] and tmp are the same object and clearing it will result in arr[0] being cleared. 因此,在您的情况下, arr[0]tmp是同一对象,清除它会导致arr[0]被清除。 Hope this helps. 希望这可以帮助。

EDIT 编辑

As a quick answer to the second part of your question: you don't need to use the tmp ArrayList inside the addArray method. 作为对问题第二部分的快速解答:您不需要在addArray方法内使用tmp ArrayList The argument of the addArray method is a reference to the object, passed by value . addArray方法的参数是对对象引用,由value传递 So changing it won't have any effect outside of the addArray method. 因此,对其进行更改不会对addArray方法产生任何影响。 Hope it's clear. 希望清楚。

是的,将对象添加到集合时不会克隆它们。

对于对象,Java总是传递参考值的副本,因此,是的,要清除的ArrayList与您添加到另一个ArrayList的ArrayList相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM