Search code examples
javadeep-copy

Java - how to copy an collections object being passed around before modification?


I am slightly new to Java and its pass-by-value concept and I am still coming to terms with it. I have the following code and questions regarding this code.

Question: 1) Will my current code do a deep copy? or I will have to do a deep copy for Class A as well?

Question: 2) will a deep copy prevent changes to my para1 that I am passing around the classes?

Thanks in advance for your help.

Regards, Atul.

public class A {
   private Double value;
}

public class I {
private Hashtable<Long, A> f2 = null;        

    I(I oldI){
        f2 = new Hastable<Long, A>(oldI);
    }
}

public class k {

private HashMap<Long, I > ob1 = null;


private HashMap<Long, I> ob2 = null; 

    k(Vector<I> para1){
    ob1 = new HashMap<Long, I >();
    for(int i=0; i < para1.size(); i++){
                    /* Question: 1  */
        ob1.put((long) i, new I(para1.get(i)));
    }
    }
}

Solution

  • 1.) No your current code does not give you a deep copy. And if you want wo make a deep copy, you'd have to clone complex inner classes too.

    2.) Yes, a deep copy would prevent changes from object 1 if you make changes in object 2, even if object 2 is a clone of object 1.

    http://www.javaworld.com/javaworld/javatips/jw-javatip76.html