Making a copy versus changing a pointer location.

I’d like to copy and Object, not set a pointer. Like so:

MyObject o1 = new MyObject();
MyObject o2 = o1;

Seems as though o2 is just pointing to o1. I want o2 to be a copy of o1. How might I do that?

You always only have references to objects. So in your example…

MyObject o1 = new MyObject();
MyObject o2 = o1;

…neither o1 or o2 are the object. It’s just a reference. So if you do something like…

MyObject o1 = new MyObject(“one”);
MyObject o2 = o1;
MyObject o1 = new MyObject(“two”);

o2 will hold a reference to “one” whereas o1 will hold a reference to “two” (the new object). [And if there isn’t a reference to an object it will get garbage collected]

If you want to create a copy you need to use clone(); like…

MyObject o1 = new MyObject(“one”);
MyObject o2 = o1.clone();

then you’ll have two different but (content wise) identical objects.

Btw you’ll need to implement the Cloneable interface.
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Cloneable.html

Thank you again, sir.