Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to transfer value from an ArrayList to another

Tags:

java

With 2 ArrayList, I was wondering if the best way from transforming the 1st one into a "copy" of the second one is to go like

myFirstArray.clear();
myFirstArray.addAll(mySecondArray);

or

myFirstArray = mySecondArray.clone();

What are the main differences between those two method, which on is preferrable and is there another "easier" or "cleaner" solution. Thanks for any tips

EDIT : I use this copy for replacing an Array of item im currently working with the one where I store the item I'll work with in the next loop. At the end of the loop I replace my currentArrayList with my futurArrayList and I clear my futurArraylist in order to add new item in it (i hope its clear enough)

like image 303
WizLiz Avatar asked Jul 23 '13 12:07

WizLiz


People also ask

How do I move data from one ArrayList to another?

In order to copy elements of ArrayList to another ArrayList, we use the Collections. copy() method. It is used to copy all elements of a collection into another. where src is the source list object and dest is the destination list object.

How do I pass a value from a list to another list?

To append a list to another list, use extend() function on the list you want to extend and pass the other list as argument to extend() function.

Can you set 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.

How do I copy a list into an ArrayList?

Constructor A simple way to copy a List is by using the constructor that takes a collection as its argument: List<Plant> copy = new ArrayList<>(list); Since we're copying references here, and not cloning the objects, every amends made in one element will affect both lists.


1 Answers

The first one replaces the content of the list by another content. The second one creates another ArrayList instance, leaving the previous one untouched.

If the list is referenced by some other object, and you want this other object to be untouched, use the second one. If you want the other object to also have the new content, use the first one.

If nothing else referenced the list, it doesn't matter much. The second one will reduce the memory used in case you replace the content of a huge list by a few elements.

like image 190
JB Nizet Avatar answered Oct 20 '22 08:10

JB Nizet