I'm writing a server & client app that will except multiple clients (For learning sakes.) I have not grasped the concepts of a copy of a OBJECT or a ref to a packet.
If I write a method in my server such as....
To be sure in my program I actually wrote a Constructor that copies the contents of one object to the new object.. And I think someday when I'm smarter, I can use the "opperand=" method in a class to copy, but not sure how that works Or I could be confusing that with c++..<SMILE
Not sure If I need to go that extra step.. Also I read a article on clone object.. (which adds a whole new level of confusion but seems to be way of handling it.)
Java doesn't have operator overloading, so changing what = does is not going to happen. It always copies the value; for references, the value is not the object itself but a reference to the object.
One important thing to understand is that in Java, variables are references to objects. A variable is not the object itself - it is a reference to the object.
With this in mind, let's look what this code does:
Line 1: Declares a variable copyMO, creates a new MyOBJ object and makes copyMO refer to that new object. NOTE: Creating the new object is unnecessary, since in the next line you're making copyMO refer to another object, throwing away the new object that you're creating here.
Line 2: Make copyMO refer to the same object as that mo refers to. NOTE: This does not copy the object that mo refers to.
Line 3: Add the object to the queue. This actually adds a reference to the object to the queue.
Line 4: Set copyMO to null.
The effect of these four lines of code is essentially the same as simply doing:
Declaring a new variable, assigning it to the same object as mo, and then adding it to the queue through the new variable is unnecessarily complicated and doesn't do anything to create a copy of the actual object. If you really want to copy the object, then Rob's suggestion to create copy constructor is good. You would use it like this:
quick explanation of where the items are coming from to help explain my confusion. I have packet objects coming in over a socket stream I want to put them in the que to be handled by the server and dispatched back out to the clients. So the object is created by the ois.readObject() and if i add this to my que wont my que point to the same memory if more then 1 object is added? (thus the reason I need to make more copies.)
joe vasher wrote:So the object is created by the ois.readObject() and if i add this to my que wont my que point to the same memory if more then 1 object is added? (thus the reason I need to make more copies.)
In this case, it is not necessary to copy the objects. ois.readObject() will create a new object each time you read an object; no need to copy that object. Just put it in the queue.