简体   繁体   中英

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

You need to implement a deep copy, ie 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.

发生这种情况是因为你是clonig的ArrayList,即myAr包含(不是原始类型)。为了完成这个任务,你必须使用for循环单独复制所有元素。

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

.clone() creates a shallow copy (ie 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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