清除特定的ArrayList,而不是它的所有副本的 [英] Clearing a specific arraylist instead of all the copies of it
问题描述
当我清楚我的ArrayList之一,它可以清除ArrayList的所有副本。
When I clear one of my arraylist, it clears all the copies of that arraylist.
ArrayList<String> testa = new ArrayList<String>();
ArrayList<String> testb = new ArrayList<String>();
testa.add("Dog");
testb = testa;
testa.clear();
现在TESTB也被清除。反正有没有避免这种情况?
Now testb also gets cleared. Is there anyway to avoid this?
推荐答案
由于 TESTB
被refferring到种皮
。这是当一个改变b也可以改变。
Since testb
is refferring to testa
.That's when a changes b also changes.
当你做 TESTB =种皮;
这就像,
+-----+
| testa |--------\
+-----+ \ +----------------+
--->| (same list) |
+-----+ / | testa |
| testb |--------/ +----------------+
+-----+
如果你不希望出现这种情况,创建一个新独立的ArrayList
。
If you don't want that, create a new independent ArrayList
.
在通过实际列表新的<一个href=\"http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#ArrayList%28java.util.Collection%29\"相对=nofollow> 构造
,
Passing the actual list to new constructor
,
ArrayList<String> testa = new ArrayList<String>();
testa.add("Dog");
ArrayList<String> testb = new ArrayList<String>(testa);
testa.clear();
或<一个href=\"http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#addAll%28java.util.Collection%29\"相对=nofollow> 的addAll
方法
ArrayList<String> testa = new ArrayList<String>();
testa.add("Dog");
ArrayList<String> testb = new ArrayList<String>();
testb.addAll(testa);
testa.clear();
这篇关于清除特定的ArrayList,而不是它的所有副本的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!