Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will addAll function in Java make a copy

Tags:

When list.addAll(list2) is called will objects in lists be copied to list? or just copy their references... did not find any explanation on javadoc...

like image 789
Richard Avatar asked Oct 28 '11 03:10

Richard


People also ask

Does addAll create a deep copy?

Now we know that copy constructor or various collection classes like addAll() method of List or Set, only creates a shallow copy of Collection and both original and cloned Collection points to the same objects. To avoid this, we can deep copy collection, iterating over them and cloning each element.

What does addAll function do in Java?

addAll(set); Here, we have used the addAll() method to add all the elements of the hashset to the arraylist. The optional index parameter is not present in the method. Hence, all elements are added at the end of the arraylist.

What does addAll return?

Return value The addAll() method returns true if the collection changes as a result of elements being added into it; otherwise, it will return false .

What is the difference between ADD and addAll in list in Java?

add is used when you need to add single element into collection. addAll is used when you want to add all elements from source collection to your collection.


2 Answers

No copy of the objects or their data are made; their references are simply added to the list object.

like image 79
Will Chesterfield Avatar answered Sep 27 '22 20:09

Will Chesterfield


No, the objects will not be copied; references to the same objects will be added to the list.

like image 30
Ernest Friedman-Hill Avatar answered Sep 27 '22 20:09

Ernest Friedman-Hill