I have deep nested structures, and methods like “remove(<Something>)“, “contains(<Something>)” etc. rely on access to the original reference in order to remove it etc. (a copy of the reference won’t do).
How have people best worked around this so they can still conveniently add, remove, test for etc. the object they want, within different arbitrary methods and constructors etc., without adding any unnecessary complexity or any unnecessary loss in performance?
Methods like
removeandcontainswork fine with pass by value. The reason is that the even though the references are copied, they copy has the same value of the original. Just look at the Collections API. If you do something like (psuedocode)and then you do
both
listandobject 1are passed by value, so in themyRemovemethod they are copies of the original reference. If inmyRemoveyou dothe object is still removed from the list no problem. Furthermore, since the
listandobject1references in both scopes point to the same underlying objects, the list reference in the calling scope refers to the list that has the object removed.The only time you would need pass by reference semantics is if you want to modify a reference in a method and have the modification apply in the scope that called the method.
So if you want to do
and have
changeListchange where myList points in the calling scope, it wont work without some trickery. The trickery is called double indirection. Basically, you create an object that has an instance of what you want to be able to access with pass by reference semantics, and you pass the container object around.So
now you can pass an instance of
MyContainerinto a method, and change the list value, and in the calling scope where thelistpoints will be changed. Note that you are not doing anything special here, everything is still pass by value.