How do I copy an object in Java?

Consider the code below: DummyBean dum = new DummyBean(); dum.setDummy(“foo”); System.out.println(dum.getDummy()); // prints ‘foo’ DummyBean dumtwo = dum; System.out.println(dumtwo.getDummy()); // prints ‘foo’ dum.setDummy(“bar”); System.out.println(dumtwo.getDummy()); // prints ‘bar’ but it should print ‘foo’ So, I want to copy the dum to dumtwo and change dum without affecting the dumtwo. But the code above is not doing … Read more

Deep cloning objects

I want to do something like: MyObject myObj = GetMyObj(); // Create and fill a new object MyObject newObj = myObj.Clone(); And then make changes to the new object that are not reflected in the original object. I don’t often need this functionality, so when it’s been necessary, I’ve resorted to creating a new object … Read more

What is the most efficient way to deep clone an object in JavaScript?

This question’s answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions. What is the most efficient way to clone a JavaScript object? I’ve seen obj = eval(uneval(o)); being used, but that’s non-standard and only supported by Firefox. I’ve done things like obj = … Read more

How do you make a deep copy of an object?

A safe way is to serialize the object, then deserialize. This ensures everything is a brand new reference. Here’s an article about how to do this efficiently. Caveats: It’s possible for classes to override serialization such that new instances are not created, e.g. for singletons. Also this of course doesn’t work if your classes aren’t Serializable.