Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 816
CQM Avatar asked Dec 09 '11 05:12

CQM


People also ask

How do I add all elements from one ArrayList to another?

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.

Can you make an ArrayList equal to another 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.

Can you copy an 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.

Can you put an ArrayList in an ArrayList?

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.


1 Answers

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.

like image 158
Artem Avatar answered Oct 07 '22 07:10

Artem