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?
You can use such trick:
or use
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.
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:
fill list1 in whatever way you currently are.
Straightforward way to make deep copy of original list is to add all element from one list to another list.
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 anotherArrayList
:Edit: As Bohemian points out in the comments below, is this what you're asking? By doing the above, both
ArrayList
s (myTempObject
andmyObject
) would contain references to the same objects. If you actually want a new list that contains new copies of the objects contained inmyTempObject
then you would need to make a copy of each individual object in the originalArrayList
You need to
clone()
the individual object.Constructor
and other methods perform shallow copy. You may try Collections.copy method.Here is a workaround to copy all the objects from one arrayList to another:
subList is intended to return a List with a range of data. so you can copy the whole arrayList or part of it.