user25
user25

Reputation: 3195

Difference between ArrayList.addAll(list) and new ArrayList<>(list) for content copying

I know that list2.addAll(list1) allows us to append additional objects to list2 from list1 if list2 already had some objects before calling this method

But I don't append anything and I want to know the difference of the next case

Would be there any difference when making a copy of a list using next methods

For example I have a list of some objects (list1) and I want to make a copy of it, copy its content to another list (to a new list - list2)

List<Foo> list1 = new ArrayList<>();
list1.add(new Foo());
...

Method 1

List<Foo> list2 = new ArrayList<>(list1);

Method 2

List<Foo> list2 = new ArrayList<>();
list2.addAll(list1);

Update

Actually even IntelliJ IDEA suggests me to convert method 2 to method 1:

enter image description here

Upvotes: 2

Views: 1338

Answers (1)

Let&#39;s_Create
Let&#39;s_Create

Reputation: 3613

Yes, I think method 2 would be a little inefficient and my point of view is:

When you do this:

List<Object> list2 = new ArrayList<Object>(list1);

ArrayList already knows the size it needs to allocate to the memory that is a count of the Object in list1.

While in method 2 it creates a list2 object with default size. At it updates itself when you perform an add operation. As it will be an extra operation.

Upvotes: 6

Related Questions