Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy an object by value, not by reference [duplicate]

Tags:

java

I want to make a copy of an object, then after some logic, re-assign the original object the value of the copy.

example:

User userCopy = //make a copy  foreach(...) {   user.Age = 1;   user.ID = -1;    UserDao.Update(user)     user = userCopy;   } 

I don't want a copy by reference, it has to be a copy by value.

The above is just a sample, not how I really want to use it but I need to learn how to copy by value.

like image 501
Blankman Avatar asked Apr 12 '10 17:04

Blankman


People also ask

How do you copy an object by value not by reference?

assign() method is used to copy all enumerable values from a source object to the target object. Example: const obj = {a:1,b:2,c:3}; const clone = Object. assign({},obj); console.

How do I make a copy of an existing object?

To create a copy of an existing object in the vault, right-click the object of your choice and select Make Copy from the context menu. This command creates an entirely new object using the metadata and contents of the source object.

Why are objects copied by references?

Objects are assigned and copied by reference. In other words, a variable stores not the “object value”, but a “reference” (address in memory) for the value. So copying such a variable or passing it as a function argument copies that reference, not the object itself.


1 Answers

Here are the few techniques I've heard of:

  1. Use clone() if the class implements Cloneable. This API is a bit flawed in java and I never quite understood why clone is not defined in the interface, but in Object. Still, it might work.

  2. Create a clone manually. If there is a constructor that accepts all parameters, it might be simple, e.g new User( user.ID, user.Age, ... ). You might even want a constructor that takes a User: new User( anotherUser ).

  3. Implement something to copy from/to a user. Instead of using a constructor, the class may have a method copy( User ). You can then first snapshot the object backupUser.copy( user ) and then restore it user.copy( backupUser ). You might have a variant with methods named backup/restore/snapshot.

  4. Use the state pattern.

  5. Use serialization. If your object is a graph, it might be easier to serialize/deserialize it to get a clone.

That all depends on the use case. Go for the simplest.

EDIT

I also recommend to have a look at these questions:

  • Clone() vs. Copy constructor
  • How to properly override clone method
like image 135
ewernli Avatar answered Sep 21 '22 13:09

ewernli