How do you copy objects in Java? Every copy I currently make points to the same location in memory. Really frustrating as I transition from C++.
The object I want to make a copy of also is holding an object from the Calendar Class inside of it.
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
How do you copy objects in Java? Every copy I currently make points to the same location in memory. Really frustrating as I transition from C++.
The object I want to make a copy of also is holding an object from the Calendar Class inside of it.
You must create a deep copy of the object, and there are many ways to do so (constructors, setters, Object.clone). For more information on cloneable, shallow copies, and deep copies see clone (Java method) - Wikipedia, the free encyclopedia
I guess you're copying the object reference rather than the object itself. You'll find that object references in Java are a bit like pointers in C++ (with some restrictions). You never really see a 'raw' object in Java, they're always handled by reference variables which refer (point) to the actual object. When you declare a Java object reference variable, it is null until you initialize it to refer (point) to an object of that type.
If you have copied the object to new object using assignment operator then it surely is an object reference that will point to earlier object. That could be the reason you see same copies through different object reference. In case if you are looking for multiple copies you should clone the original object.