lalli
lalli

Reputation: 6303

Inserting an object into 2 Collections

I have 2 lists and am a little confused about adding an object into both of them like this:

TestClass e;
List lst1;
LinkedList lst2;
...
lst1.add(e);
lst2.add(e);

Will lst1 and lst2 have copies of e? or the reference to the same object e?
If the first is true, how can the code make copies of e if TestClass is not clonable?

Upvotes: 1

Views: 106

Answers (4)

aioobe
aioobe

Reputation: 421020

Will lst1 and lst2 have copies of e?

Yes.

Both lists will have a copy of the value contained in e. (Note though, that e contains a reference and not an actual object.)

This means that

  1. Both lists will have one copy each of the reference to the TestClass object which e refers to at the point of the add.

  2. Changes to the TestClass object will be visible from both lists references.

  3. Performing e = null after the add will not affect the content of the lists (the lists contain copies, remember? ;-)

Upvotes: 1

Marsellus Wallace
Marsellus Wallace

Reputation: 18601

This goes back to the old question of passing by reference vs passing by value...

See this stackoverflow question

Both lst1 and lst2 will contain a value (represented by the variable e) that will tell the JVM how to find the TestClass instance in the Heap Memory. If you modify the instance (there is only one instance) by accessing it through e, lst1, or lst2 the changes will be visible everywhere!

The only way to change this behavior is to override the Object clone() in TestClass function and passing e.clone() to the add(...) function. Please refers to the documentation

If you cannot modify the TestClass for any reasons you can also clone the instance by yourself (basically you implement clone() outside TestClass). Create a new TestClass instance e2 with the new operator and then get its instance variables (be careful is it contains other custom objects) from e through its 'getters' and set the values to e2 through its 'setters'. This is ugly as hell and I hope you refuse to do it...

Upvotes: 0

Paul Bellora
Paul Bellora

Reputation: 55223

The second is true: both collections will hold a reference to that same object.

Upvotes: 2

Daniel A. White
Daniel A. White

Reputation: 190943

They will have the same reference. You will have to manually copy values over if you want it to be 2 distinct properties.

Upvotes: 2

Related Questions