We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
Page Index Toggle Pages: 1
Copy an object (Read 433 times)
Copy an object
Apr 22nd, 2009, 4:28am
 
Hey community,

a short question: how can I copy an object?
I have a class Line and want to copy a specific Line L and name its copy Lcopy.
The code that I have now is:
Code:

for (int j=0; j<lines.size(); j++) {
L = (Line) lines.get(j);
if (L.ID1 == N.ID) { linesCopy.add(L); }
else if (L.ID2 == N.ID) {
Lcopy = L; // the current copy code... (not working...)
Lcopy.switchIDs();
linesCopy.add(Lcopy);
}
}


Unfortunately it now still uses the object L instead of Lcopy, while I want Line L to be unharmed. How can I guarantee this?

Thanks in advance
Re: Copy an object
Reply #1 - Apr 22nd, 2009, 8:14am
 
A compilable example might help others see exactly what is happening.

One thought is that you are using
Lcopy = L;

Which makes Lcopy point to the same object in memory as L, rather than creating a duplicate.
Re: Copy an object
Reply #2 - Apr 23rd, 2009, 1:22am
 
There is no built in Java method to copy an object: it is just too complex. Some objects reference others objects - if the latter are immutable (eg. strings), they can be shared by all copies. But some referenced objects must be duplicated as well, and can reference other objects, etc.

One solution is to use clone() or, perhaps simpler, to make a copy constructor.

Example of the latter (working well for such simple objects we do in P.):

Code:
class Stuff
{
 int x, y;
 color c;
 String m;
 // Regular constructor
 Stuff(int xx, int yy, color cc, String msg)
 {
   x = xx; y = yy; c = cc; m = msg;
 }
 // Copy constructor
 Stuff(Stuff s)
 {
   this(s.x, s.y, s.c, s.m);
 }
 String toString()
 {
   return "Stuff: " + x + " " + y + " " + hex(c) + " " + m;
 }
}

void setup()
{
Stuff s1 = new Stuff(10, 10, #FF0000, "First stuff");
println(s1);
// Copy
Stuff s2 = new Stuff(s1);
println(s2);
// Alter the first
s1.x = 20; s1.m += ". Yeah!";
println(s1);
println(s2);
// Alter the second
s2.y = 20; s2.m += ". Right.";
println(s1);
println(s2);
}
Page Index Toggle Pages: 1