How do I copy the contents of one ArrayList into another?
Asked Answered
I

13

96

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?

Iver answered 9/12, 2011 at 5:59 Comment(3)
You can use List.addAll. But if you need to retain all the objects then clearing the temp list is not really going to clear a whole lot of memory. Because your are only trying to clear the references, as far as objects you are trying to keep them.Iene
As far as I know this answer is still valid: #716150Noli
It's hard to interpret what you are really trying to achieve. You need to explain your situation.Iene
M
154

You can use such trick:

myObject = new ArrayList<Object>(myTempObject);

or use

myObject = (ArrayList<Object>)myTempObject.clone();

You can get some information about clone() method here

But you should remember, that all these ways will give you a copy of your List, not all of its elements. So if you change one of the elements in your copied List, it will also be changed in your original List.

Manatee answered 9/12, 2011 at 6:1 Comment(4)
assign by value in Java is something that is reserved for primitive types (int, byte, char, etc.) and literals. Unless you explicitly tell Java to copy something that is derived from Object it'll always assign by reference. By the way clone() is a shallow copy and will not copy the contained Objects but rather references to them. If you want to make a deep-copy take a look at: #64536Boneyard
@Boneyard - Java is only call by and assign by value. Non-primitive type variables contain reference values which are assigned or passed.Underside
Please why can't I do oldList = newList ?Borowski
@Borowski oldList = newList will copy reference of the newList to oldList, any change in newList will be reflected in the oldList also. That is not the intended behaviour.Foregut
C
44

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.

Convolve answered 13/3, 2015 at 13:42 Comment(2)
How to stop affect to another list is there any other way we can handle thisKatrinka
@Katrinka - refer this #716150Walcott
U
17

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

Underside answered 9/12, 2011 at 6:3 Comment(4)
In this case it would work fine as calling clear() on the ArrayList myTempObject would have no effect on the objects contained therin. If he wanted new copies of the objects contained in the list, that's another story, but that's not what I interpreted this question as asking.Underside
You know I think you're right. I mis-interpreted the question. He was worried that clearing one would clear the other. Comment deleted.Genuflection
@Genuflection - I think it was a fair comment and I edited my post to reflect it. I didn't consider that might be the OP's intent when reading his question.Underside
@BrianRoach How to take a copy of a ArrayList inside an ArrayList.Cottar
P
8

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);
}
Portamento answered 10/4, 2015 at 17:10 Comment(0)
R
7

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.

Rockel answered 6/1, 2016 at 20:27 Comment(1)
oldList and newList would still be dependent. If you were to remove an element from the newList, it would also remove it from the oldList. Did you even test this?Fermium
O
4

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());
}
Oujda answered 27/10, 2017 at 5:24 Comment(0)
W
3

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

Wilscam answered 9/12, 2011 at 6:5 Comment(1)
Collections.copy is broken. First, it's misleading by saying that it copies elements, whereas it only references them in a new list. Second, you need to already have a destination list having the size not lower than the source list...Gremlin
C
1

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.

Churchill answered 23/11, 2017 at 5:32 Comment(1)
The two lists would still be dependent. Try using the remove method on the duplicate and print the original.Fermium
Z
0

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.

Zygote answered 7/2, 2014 at 7:11 Comment(0)
L
0

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);
Limousine answered 15/11, 2017 at 11:53 Comment(0)
V
0

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.

Verona answered 23/3, 2019 at 2:10 Comment(0)
Q
0

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!!

Quintus answered 31/7, 2019 at 9:51 Comment(0)
M
0

The simplest way is:

ArrayList<Object> myObject = new ArrayList<Object>();
// fill up data here
ArrayList<Object> myTempObject = new ArrayList(myObject);
Mauldon answered 16/5, 2021 at 22:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.