2

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

1
  • 1
    addAll also does some size checks (whether to enlarge the underlying array etc). Commented Jan 26, 2019 at 18:24

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.