0

I have two lists, ListA and ListB and I want to copy ListB to ListA.

What is the difference between the following, in terms of complexity and result:

  1. ListA = ListB;
  2. ListA = new ArrayList(ListB);
1
  • 1) copies the reference to a List 2) creates a new list with a copy of the references to the elements in the list. Commented Jan 18, 2013 at 13:12

3 Answers 3

7

With listA = listB, there is only one list. So if you call listA.add(something);, it will add to listB too.

With listA = new ArrayList(listB); there are two lists (which happen to contain the same objects). So if you call listA.add(something);, it will NOT add anything to listB.

In terms of complexity, the first one is a simple assignement (i.e. runs in constant time), whereas the second runs in O(n), n being the size of listB.

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

Comments

6

In the first case there is no copying at all. Just aliasing: listA can be viewed as a synonym, alias for ListB.

This is, naturally, due to Java's exclusive usage of reference types. No type in Java can actually hold an object as its value.

Comments

3

for ListA = ListB

You are not copying the list, you are just assigning another alias (reference) to that object.

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.