HOW DO I COPY AN OBJECT IN JAVA?

Pooja Malohtra

Total Post:47

Points:331
Posted by  Pooja Malohtra
Java 
 731  View(s)
Ratings:
Rate this:
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 I want to change 'dum' without affecting the 'dumtwo'. But the above code is not doing that. When I change something in 'dum', the same change is happening in 'dumtwo' also.

I guess, when I say dumtwo = dum, Java copies the reference only. So, is there any way to create a fresh copy of 'dum' and assign it to 'dumtwo' ?
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: How do I copy an object in Java?

    public class Deletable implements Cloneable{
        private String str;
        public Deletable(){
        }
        public void setStr(String str){
            this.str = str;
        }
        public void display(){
            System.out.println("The String is "+str);
        }
        protected Object clone() throws CloneNotSupportedException {
            return super.clone();
        }
    }
    and wherever you want to get another object, simple perform cloning. e.g:

    Deletable del = new Deletable();
    Deletable delTemp = (Deletable ) del.clone(); // this line will return you an independent
                                     // object, the changes made to this object will
                                     // not be reflected to other object


    In your case object is copied as a shallow copy, but if you need independent object you need to clone this object as deep copy.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!