WizLiz
WizLiz

Reputation: 2098

Best way to transfer value from an ArrayList to another

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)

Upvotes: 8

Views: 20602

Answers (4)

gyorgyabraham
gyorgyabraham

Reputation: 2608

Guava, guava, guava!

final List copied = ImmutableList.copyOf(originalList);

Upvotes: 0

Ortwin Angermeier
Ortwin Angermeier

Reputation: 6193

Use that:

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

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

Of course in your case, with the ArrayList, it will work as expected, you will end up with a copy of the references.

Upvotes: 1

Ankur Lathi
Ankur Lathi

Reputation: 7836

In java, though clone is ‘intended’ to produce a copy of the same object it is not guaranteed. Clone comes with lots of its and buts. So my first advice is to not depend on clones.

By default, java cloning is ‘field by field copy’ i.e. as the Object class does not have idea about the structure of class on which clone() method will be invoked. So, JVM when called for cloning, do following things:

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

  2. If the class contains members of any class type then only the object references to those members are copied and hence the member references in both the original object as well as the cloned object refer to the same object because of that cloned object changes are visible in original also.

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691755

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.

Upvotes: 13

Related Questions