-1

I'm having a trouble with using List in java.

I created a list of objects called A, then I create other list called "B", I assign A to B.

But if I use A.clear() then B also cleared:

Example:

    List<String> original = new ArrayList<String>();

    original.add("Test");

    List<String> copy = new ArrayList<String>();

    original.clear();

--> Is there any way to maintain value of B even thought A is cleared?

Toan Tran Van
  • 695
  • 1
  • 7
  • 25
  • What is `copy` used for? – ifloop Oct 29 '14 at 15:28
  • Right now, all you did was create an empty copy object in the example above. You would need to copy original into "copy" at some point before you clear original. – Vahlkron Oct 29 '14 at 15:29
  • possible duplicate of [How to clone ArrayList and also clone its contents?](http://stackoverflow.com/questions/715650/how-to-clone-arraylist-and-also-clone-its-contents) – ifloop Oct 29 '14 at 15:30
  • This is just an example to demonstrate my problem in android app – Toan Tran Van Oct 29 '14 at 15:31
  • Follow The answer by @jakubHr below. Its to do with references. List B and list A are references of the same object. Rather than copies of the same object. – IAmGroot Oct 29 '14 at 15:32

2 Answers2

3

When you set one list equal to another list, instead of copying all the values from one list to another, Java is actually making them equal to the same List object in memory. This makes the two objects connected, instead of having two separate objects with the same values.

A good way to accomplish this is by passing one list to the other when you create the object, or call the Constructor. This will perform a copy of all of the values from one object into another.

So your code would look like the following:

List<String> original = new ArrayList<String>();

original.add("Test");

List<String> copy = new ArrayList<String>(original);

original.clear();

Regards.

musgravejw
  • 46
  • 3
0

You have to copy the original List. For example, using constructor which accepts Collection.

List<String> copy = new ArrayList<String>(original);

Below code prints "A"

List<String> org = new ArrayList<String>();
org.add("A");
List<String> copy = new ArrayList<String>(org);
copy.add("B");
copy.clear();
System.out.println(org);

Keep in mind that it makes only a shallow copy of the List. It's enough for List, but if your list contains mutable objects you should create deep copy of the list.

Jakub H
  • 2,130
  • 9
  • 16