[java] How do I copy the contents of one ArrayList into another?

I have some data structures, and I would like to use one as a temporary, and another as not temporary.

ArrayList<Object> myObject = new ArrayList<Object>();
ArrayList<Object> myTempObject = new ArrayList<Object>();


//fill myTempObject here
....

//make myObject contain the same values as myTempObject
myObject = myTempObject;

//free up memory by clearing myTempObject
myTempObject.clear();

now the problem with this of course is that myObject is really just pointing to myTempObject, and so once myTempObject is cleared, so is myObject.

How do I retain the values from myTempObject in myObject using java?

This question is related to java reference variable-assignment

The answer is


Copy of one list into second is quite simple , you can do that as below:-

ArrayList<List1> list1= new ArrayList<>();
ArrayList<List1> list2= new ArrayList<>();
//this will your copy your list1 into list2
list2.addAll(list1);

Supopose you want to copy oldList into a new ArrayList object called newList

ArrayList<Object> newList = new ArrayList<>() ;

for (int i = 0 ; i<oldList.size();i++){
    newList.add(oldList.get(i)) ;
}

These two lists are indepedant, changes to one are not reflected to the other one.


Straightforward way to make deep copy of original list is to add all element from one list to another list.

ArrayList<Object> originalList = new ArrayList<Object>();
ArrayList<Object> duplicateList = new ArrayList<Object>();

for(Object o : originalList) {
    duplicateList.add(o);
}

Now If you make any changes to originalList it will not impact duplicateList.


There are no implicit copies made in java via the assignment operator. Variables contain a reference value (pointer) and when you use = you're only coping that value.

In order to preserve the contents of myTempObject you would need to make a copy of it.

This can be done by creating a new ArrayList using the constructor that takes another ArrayList:

ArrayList<Object> myObject = new ArrayList<Object>(myTempObject);

Edit: As Bohemian points out in the comments below, is this what you're asking? By doing the above, both ArrayLists (myTempObject and myObject) would contain references to the same objects. If you actually want a new list that contains new copies of the objects contained in myTempObject then you would need to make a copy of each individual object in the original ArrayList


to copy one list into the other list, u can use the method called Collection.copy(myObject myTempObject).now after executing these line of code u can see all the list values in the myObject.


You need to clone() the individual object. Constructor and other methods perform shallow copy. You may try Collections.copy method.


Came across this while facing the same issue myself.

Saying arraylist1 = arraylist2 sets them both to point at the same place so if you alter either the data alters and thus both lists always stay the same.

To copy values into an independent list I just used foreach to copy the contents:

ArrayList list1 = new ArrayList();
ArrayList list2 = new ArrayList();

fill list1 in whatever way you currently are.

foreach(<type> obj in list1)
{
    list2.Add(obj);
}

originalArrayList.addAll(copyArrayList);

Please Note: When using the addAll() method to copy, the contents of both the array lists (originalArrayList and copyArrayList) refer to the same objects or contents. So if you modify any one of them the other will also reflect the same change.

If you don't wan't this then you need to copy each element from the originalArrayList to the copyArrayList, like using a for or while loop.


Lets try the example

     ArrayList<String> firstArrayList = new ArrayList<>();
            firstArrayList.add("One");
            firstArrayList.add("Two");
            firstArrayList.add("Three");
            firstArrayList.add("Four");
            firstArrayList.add("Five");
            firstArrayList.add("Six");
            //copy array list content into another array list
             ArrayList<String> secondArrayList=new ArrayList<>();
            secondArrayList.addAll(firstArrayList);
            //print all the content of array list
            Iterator itr = secondArrayList.iterator();
            while (itr.hasNext()) {
                System.out.println(itr.next());
            }

In print output as below

One
Two
Three
Four
Five
Six

We can also do by using clone() method for which is used to create exact copy

for that try you can try as like

 **ArrayList<String>secondArrayList = (ArrayList<String>) firstArrayList.clone();**
    And then print by using iterator
      **Iterator itr = secondArrayList.iterator();
                while (itr.hasNext()) {
                    System.out.println(itr.next());
                }**

Suppose you have two arraylist of String type . Like

ArrayList<String> firstArrayList ;//This array list is not having any data.

ArrayList<String> secondArrayList = new ArrayList<>();//Having some data.

Now we have to copy the data of second array to first arraylist like this,

firstArrayList = new ArrayList<>(secondArrayList );

Done!!


Here is a workaround to copy all the objects from one arrayList to another:

 ArrayList<Object> myObject = new ArrayList<Object>();
ArrayList<Object> myTempObject = new ArrayList<Object>();

myObject.addAll(myTempObject.subList(0, myTempObject.size()));

subList is intended to return a List with a range of data. so you can copy the whole arrayList or part of it.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to reference

Method Call Chaining; returning a pointer vs a reference? When to create variables (memory management) Reference to non-static member function must be called Cannot find reference 'xxx' in __init__.py - Python / Pycharm c++ "Incomplete type not allowed" error accessing class reference information (Circular dependency with forward declaration) C++ initial value of reference to non-const must be an lvalue Dependent DLL is not getting copied to the build output folder in Visual Studio How to write to error log file in PHP How to reference Microsoft.Office.Interop.Excel dll? Linker Error C++ "undefined reference "

Examples related to variable-assignment

How to assign a value to a TensorFlow variable? Why does foo = filter(...) return a <filter object>, not a list? Creating an array from a text file in Bash Check if returned value is not null and if so assign it, in one line, with one method call Local variable referenced before assignment? Why don't Java's +=, -=, *=, /= compound assignment operators require casting? How do I copy the contents of one ArrayList into another? Python: Assign Value if None Exists Assignment inside lambda expression in Python Expression must be a modifiable L-value