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.
Printable View
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.