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?
Approach: ArrayLists can be joined in Java with the help of Collection. addAll() method. This method is called by the destination ArrayList and the other ArrayList is passed as the parameter to this method. This method appends the second ArrayList to the end of the first ArrayList.
The clone() method of the ArrayList class is used to clone an ArrayList to another ArrayList in Java as it returns a shallow copy of its caller ArrayList.
The clone() method of the java. util. ArrayList class returns a shallow copy of this ArrayList instance (i.e the elements themselves are not copied). Using this method, you can copy the contents of one array list to other.
Add all the Elements of an ArrayList to another ArrayList To add all the elements of an ArrayList to this ArrayList in Java, you can use ArrayList. addAll() method. Pass the ArrayList, you would like to add to this ArrayList, as argument to addAll() method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With