• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to create a copy of java object

 
Jignesh Patel
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
how can i create a copy of an object? (cloning???)
my requirement is to create a copy of an object. after that when i change some attributes of the original object; the copy of that object shall remain unchanged (ie it shall contain the older values of the attribute)
can anybody guide me in that with proper syntax??
tia
jignesh
------------------
 
Kaspar Dahlqvist
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there, patel_o (?) !
This is one way:
import java.io.*;
public class Q implements Cloneable {
private int i;

public Q(int i) {
this.i = i;
}
public static void main(String[] a) throws Exception {
Q q = new Q(4);
Q q2 = (Q) q.clone();
q2.i = 6;
System.out.println(q.i + ", " + q2.i);
}
}
Maybe there's another...
Hope this helps!
/Kaspar
 
Frank Carver
Sheriff
Posts: 6920
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"patel_o",
The Java Ranch has thousands of visitors every week, many with surprisingly similar names. To avoid confusion we have a naming convention, described at http://www.javaranch.com/name.jsp . We require names to have at least two words, separated by a space, and strongly recommend that you use your full real name. Please log in with a new name which meets the requirements.
Thanks.
 
Detlev Beutner
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The solution implementing Cloneable is one way, the other is a constructor with the object itself, for example:

It is a matter of taste (and maybe time), which one you prefer. The "Cloneable"-solution is somewhat more intuitive to write, whereas the "Constructor"-solution is somewhat more intuitive to read. But as said: "A matter of taste."
Ok, sometimes the "Constructor"-solution is sometimes hard to implement, depending of members.
Best regards
Detlev
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic