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