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?
Lets try the example
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
Supopose you want to copy oldList into a new ArrayList object called newList
These two lists are indepedant, changes to one are not reflected to the other one.
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.
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.
Suppose you have two arraylist of String type . Like
Now we have to copy the data of second array to first arraylist like this,
Done!!