简体   繁体   中英

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:

在此处输入图片说明

Yes, I think method 2 would be a little inefficien t 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM