Rafz Ab
Rafz Ab

Reputation: 33

How to maintain the value of old arraylist after copied to a new arraylist and manipulation

I have an arraylist as below:

ArrayList<List<Double>> myAr = new ArrayList<>();

I add the value to the array as below:

myAr.add(Arrays.asList((double)3,(double)4,(double)5,(double)6));
myAr.add(Arrays.asList((double)6, (double)8, (double)1, (double)4));

Then I assign to a new arraylist and copied myAr to temp as below:

ArrayList<List<Double>> temp = new ArrayList<>();
temp = (ArrayList<List<Double>>)myAr.clone();

I did some modification to an element as below:

temp.get(0).set(2, 9.0);

Then I display the output for both temp and myAr.

System.out.println(temp);
System.out.println(myAr);

Unfortunately, both displayed the same output. I want the myAr to be remain as it is. What can I do?

Thank you

Upvotes: 3

Views: 332

Answers (4)

Code_Bugs
Code_Bugs

Reputation: 5

Use the following code, it will work:

ArrayList<List<Double>> myAr = new ArrayList<>();

    myAr.add(Arrays.asList((double)3,(double)4,(double)5,(double)6));
    myAr.add(Arrays.asList((double)6, (double)8, (double)1, (double)4));

    ArrayList<List<Double>> temp = new ArrayList<>();

    //copy old list to new list (deep copy)
    for (List<Double> list : myAr)
    {
        temp.add(list);
    }

    //output original list  
    for (List<Double> list : myAr)
    {
        System.out.println(list);
    }

    System.out.println();
    System.out.println("Temp array");

    //editing value in new list
    temp.get(0).set(2, 11.0);

    //output new list
    for (List<Double> list : temp)
    {
        System.out.println(list);
    }

Upvotes: 0

Andy Turner
Andy Turner

Reputation: 140318

You need to implement a deep copy, i.e. you actually need to duplicate the inner lists:

ArrayList<List<Double>> temp = new ArrayList<>();
for (List<Double> list : myAr) {
  temp.add(Arrays.asList(list.toArray(new Double[0]));
}

otherwise the elements of temp and myAr point to the same underlying lists.

Upvotes: 6

Diego Martinoia
Diego Martinoia

Reputation: 4662

.clone() creates a shallow copy (i.e. it creates a new collection and copies the pointers of the values in the collection, but does not copy the values).

If you want to achieve a deep copy, use a copy constructor:

temp = new ArrayList<>(myArr);

Upvotes: -1

ValarDohaeris
ValarDohaeris

Reputation: 649

This is happening because the ArrayList you are clonig ie myAr contains(not primitive types) .To achieve this task you have to individually copy all the elements using a for loop.

Upvotes: 0

Related Questions