开发者

What's the most elegant workaround for inability to pass by reference in Java?

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 remove and contains work 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)

List list = new List();
list.add(object1) // assume you have an object1 reference

and then you do

myRemove(list, object1);

both list and object 1 are passed by value, so in the myRemove method they are copies of the original reference. If in myRemove you do

list.remove(object1);

the object is still removed from the list no problem. Furthermore, since the list and object1 references 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

List myList = new List(); 
changeList(myList); 

and have changeList change 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

class MyContainer {
    List list
}

now you can pass an instance of MyContainer into a method, and change the list value, and in the calling scope where the list points will be changed. Note that you are not doing anything special here, everything is still pass by value.


How have people best worked around this so...

By use of member fields (for working with references, not copies) and by use of inheritance and interfaces (for handling nested structures).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜