开发者

modify value in variable

I have a problem with one class in java

this class is public and ext开发者_如何学JAVAends of DefaultHandler all method of this class are public too ... but the variables are private...

My problem is that if I copy the value in other variable and modify this second variable the first change too.

is like static variables.. but they are no static... any idea!!!

thanks in advance


This is because you are actually modifying the same object. For instance, if you have

Object obj = new Object();

Object obj2 = obj;

You don't actually copy anything, you simply make obj2 "point" (not quite the right term, but it will work for now) to obj. Any changes to obj2 will be reflected in obj. Therefore, if you want to actually copy it, you need to physically create a new Object and then manually copy all of the values into the new creation. You could implement the prototype pattern to copy the object. Primitives don't behave this way so if you were to do the same thing with a double or an int for instance, it would behave the way you expect.

Does all of that make sense?


You are probably having a problem with passing by reference versus passing by value. This page explains what I mean http://www.cs.umd.edu/class/sum2004/cmsc420/sum4v3e01/node6.html.


You probably are copying a reference to a changeable object, not the object itself; so after the copy, you have two references to the same object. Changing that object through either reference will have the same effect.

I can't tell you how to copy the actual object because there's no generic way to do it, but many classes provide a copy constructor or some other way to duplicate themselves. If you need help with that you'd have to provide more details.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜