1)Is there any difference between these two keywords for the elements of collections??(Copy those elements to the other collection and addAll those elements to the other collection)
According to JavaDoc, copy() copies only from one List to another and only to the specific indices on one List to the other. addAll() just adds all items from one Collection to the other, regardless of index, and regardless the type of Collection.
Yes, there is a difference.
From the java docs:
Copy
: Copies all of the elements from one list into another. After the operation, the index of each copied element in the destination list will be identical to its index in the source list. The destination list must be at least as long as the source list. If it is longer, the remaining elements in the destination list are unaffected.
Example: Copy
[1,2,3]
to [4,5,6,7,8]
=> [1,2,3,7,8]
AddAll
: Adds all of the specified elements to the specified collection
Example: AddAll
of [1,2,3]
to [4,5,6,7,8]
=> [4,5,6,7,8,1,2,3]
For starters, Collections.copy()
overwrites the elements in the destination list, and does not change the size of the list. The .addAll()
method adds elements to the end of the list, does not overwrite anything, and increases the length of the list by however many elements were added.