Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do i create a copy of an object in java, instead of a pointer

Lets say i have an object that i created. I edited some values in it so it is different than the new object() that i referenced. Lets call that object f1. Now i want another object called f2 to be a copy of f1 but not a pointer, so that when i change a value in f2, it does not also change f1. How would i go about doing this in java?

like image 939
Ephraim Avatar asked Mar 25 '11 17:03

Ephraim


People also ask

Can you make a copy of an object in Java?

Clone() method in Java In Java, there is no operator to create a copy of an object. Unlike C++, in Java, if we use the assignment operator then it will create a copy of the reference variable and not the object.

How do you clone an object in Java?

The clone() method of Object class is used to clone an object. The java. lang. Cloneable interface must be implemented by the class whose object clone we want to create.

Which tool is used to create a copy of object?

Answer: clone tool is used to create a duplicate copy of a file.


2 Answers

First, have your class implement the Cloneable interface. Without this, calling clone() on your object will throw an exception.

Next, override Object.clone() so it returns your specific type of object. The implementation can simply be:

@Override
public MyObject clone() {
    return (MyObject)super.clone();
}

unless you need something more intricate done. Make sure you call super.clone(), though.

This will call all the way up the hierarchy to Object.clone(), which copies each piece of data in your object to the new one that it constructs. References are copied, not cloned, so if you want a deep copy (clones of objects referenced by your object), you'll need to do some extra work in your overridden clone() function.

like image 137
Jonathan Avatar answered Oct 29 '22 08:10

Jonathan


Most objects have a method clone() that will return a copy of that object, so in your case

f2 = f1.clone()
like image 33
Bobby Avatar answered Oct 29 '22 10:10

Bobby