Kelvin Yu
Kelvin Yu

Reputation: 23

Clearing a specific arraylist instead of all the copies of it

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();

Now testb also gets cleared. Is there anyway to avoid this?

Upvotes: 0

Views: 104

Answers (3)

Suresh Atta
Suresh Atta

Reputation: 122026

Since testb is refferring to testa.That's when a changes b also changes.

When you do testb = testa; it's like ,

+-----+
| testa |--------\
+-----+         \    +----------------+
                 --->| (same list)    |
+-----+         /    |  testa         |
| testb |--------/   +----------------+
+-----+

If you don't want that, create a new independent ArrayList.

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();

or with addAll method

  ArrayList<String> testa = new ArrayList<String>();
  testa.add("Dog");
  ArrayList<String> testb = new ArrayList<String>();
  testb.addAll(testa);
  testa.clear();

Upvotes: 3

Makoto
Makoto

Reputation: 106508

At this point:

ArrayList<String> testa = new ArrayList<String>();
ArrayList<String> testb = new ArrayList<String>();

testa and testb are their own, separate, unique instances, which point to two different ArrayList references. If you change one, you don't affect the other.

At this point:

testb = testa;

You have now set testb to point to the same reference as testa. Anything done with testb will affect testa, and vice versa.

If you want to copy the elements from testa to testb, new an instance of an ArrayList with testb as your argument:

testb = new ArrayList<>(testa);

Upvotes: 1

sergeyan
sergeyan

Reputation: 1183

    ArrayList<String> testa = new ArrayList<String>();
    ArrayList<String> testb = new ArrayList<String>();
    testa.add("Dog");
    List<String> testb = new ArrayList<String>(testa);
    testa.clear();

Upvotes: 1

Related Questions