94

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?

Niroshan
  • 2,064
  • 6
  • 35
  • 60
CQM
  • 42,592
  • 75
  • 224
  • 366
  • 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. – Bhesh Gurung Dec 09 '11 at 06:09
  • As far as I know this answer is still valid: http://stackoverflow.com/questions/715650/how-to-clone-arraylist-and-also-clone-its-contents – home Dec 09 '11 at 06:17
  • 2
    It's hard to interpret what you are really trying to achieve. You need to explain your situation. – Bhesh Gurung Dec 09 '11 at 06:25

13 Answers13

151

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.

mauriii
  • 486
  • 2
  • 6
  • 17
Artem
  • 4,347
  • 2
  • 22
  • 22
  • 7
    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: http://stackoverflow.com/questions/64036/how-do-you-make-a-deep-copy-of-an-object-in-java – PeterT Dec 09 '11 at 06:08
  • @PeterT - Java is *only* call by and assign by value. Non-primitive type variables contain *reference values* which are assigned or passed. – Brian Roach Dec 09 '11 at 06:10
  • Please why can't I do `oldList = newList` ? – X09 May 18 '17 at 16:14
  • 2
    @X09 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. – Sreekanth Karumanaghat Jul 04 '17 at 09:38
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.

Dhananjay M
  • 1,851
  • 22
  • 18
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

Brian Roach
  • 76,169
  • 12
  • 136
  • 161
  • 1
    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. – Brian Roach Dec 09 '11 at 06:15
  • You know I think you're right. *I* mis-interpreted the question. He was worried that clearing one would clear the other. Comment deleted. – Bohemian Dec 09 '11 at 06:27
  • @Bohemian - 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. – Brian Roach Dec 09 '11 at 06:30
  • @BrianRoach How to take a copy of a ArrayList inside an ArrayList. – Arun PS Jul 23 '15 at 07:30
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);
}
PaulC
  • 81
  • 1
  • 1
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.

Java Main
  • 1,521
  • 14
  • 18
  • 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? – Michael Mar 10 '21 at 02:53
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());
                }**
Maaz Patel
  • 756
  • 2
  • 7
  • 20
3

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

KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
  • 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... – ACV Feb 03 '17 at 14:22
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.

  • The two lists would still be dependent. Try using the remove method on the duplicate and print the original. – Michael Mar 10 '21 at 03:02
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.

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

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

0

The simplest way is:

ArrayList<Object> myObject = new ArrayList<Object>();
// fill up data here
ArrayList<Object> myTempObject = new ArrayList(myObject);
Neel Alex
  • 605
  • 6
  • 10