开发者

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 开发者_StackOverflow中文版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?


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


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


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? ;-)


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...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜