Best way to pass value from ArrayList to another

With 2 ArrayList, I was wondering if the best way to turn the 1st into a “copy” of the second is to go like

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

or

 myFirstArray = mySecondArray.clone(); 

What are the main differences between the two methods, which are preferred and there is another “lighter” or “cleaner” solution. Thanks for any advice.

EDIT: I use this copy to replace the array of the im element, which currently works with where I store the element that I will work with in the next loop. At the end of the loop, I replace my currentArrayList with my futurArrayList, and I clear my futurArraylist to add a new element to it (I hope it is clear enough)

+7
java
source share
4 answers

The first replaces the contents of the list with other content. The second creates another instance of ArrayList, leaving it as it was.

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

If nothing is mentioned in the list, it does not really matter. The second will remove the memory used if you replace the contents of a huge list with several items.

+12
source share

Use this:

 List<Object> first = ... ArrayList<Object> second = new ArrayList<>(first); 

I also suggest that you do not use clone() . It is better to use a copy constructor or some factory method. Take a look at here .

Of course, in your case with ArrayList it will work as expected, you will get a copy of the links.

+1
source share

In java, although the clone is designed to create a copy of the same object, it is not guaranteed. The clone comes with a lot of it and noses. Therefore, my first advice is not to depend on clones.

By default, java cloning is a field with a copy of the field, that is, since the Object class has no idea about the structure of the class on which the clone () method will be called. So, the JVM, when cloning is required, does the following:

  • If the class has only primitive data type members, then a new copy of the object will be completely created and a copy of the object will be returned.

  • If the class contains members of any type of class, then only the object of the link to these participants is copied and, therefore, the member in the original object and in the cloned object refer to the same object because the cloned object changes are also visible in the original.

+1
source share

Guava, guava, guava!

 final List copied = ImmutableList.copyOf(originalList); 
0
source share

All Articles