开发者

How to pass mutable objects by value to java

Is there any way that I can pass mutable Objects by value to a function in java?

What I actually want is to pass an object to a method, do some operations on it (change it) and again cal开发者_开发问答l that method with that old object only(not the changed value).

here is some sample:

    { MyObj obj = new MyObj(); obj.setName("name");

    append(obj); 
    System.out.println(obj.name);

    prepend(obj); 
    System.out.println(obj.name);

    }

    void append(MyObj obj){ obj.name+="1"; }

    void prepend(MyObj obj){ String a = "1"; obj.name=a+obj.name; }

At the end of this code, I want output as:

name1
1name


Objects themselves aren't passed at all in Java. Ever.

But everything is passed by value - where the only things that can be passed are primitive values and references.

It's not quite clear what you're trying to do - is the idea that you'd like to have a method with (say) a StringBuilder parameter, but without any changes made to the object from within the method being visible to the caller? If so, you basically need to clone the object yourself.


Unfortunately, no. Java never passes Objects by value, it passes the reference of the object by value.

Explanation from here:

What's really happening is that objects are always held by reference in java -- never by value -- and the references are, indeed, being passed by value.


Why do you need to do this? If you don't change the object, then it doesn't matter. If you do change the object, and don't want to affect the caller's object, then just make a copy locally. But I would guess that at least 90% of the time people think they need to do that, they really don't.

Show some code. What are you really trying to do?


AFAIK immutable/mutable is not related with passing by value/reference. Strings are passed by reference, not value. What makes string immutable is design of string class itself. Perhaps you may explain a bit more what you looking for.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜