2

I want to make a deep copy of a generic list in Java. How could I improve this code?

public interface Deep{}
public class Class1() implements Deep{
    public Class1(Class1 o){
        //implementation of deep copy
    }
}   

public class Class2() implements Deep{
    public Class2(Class2 o){
        //implementation of deep copy
    }
}

Implementing deepCopy of List in another class:

public List<Deep> deepCopy(List<Deep> inList){
    if(inList.get(0) instanceof Class1){
        List<Deep> newList=new ArrayList<Class1>();
            for (Deep deep : inList) 
            newList.add(new Class1((Class1) deep));
            }
    else if(inList.get(0) instanceof Class2){
        List<Deep> newList=new ArrayList<Class2>();
            for (Deep deep : inList) 
            newList.add(new Class2((Class2) deep));
                  }
}

And here is the call:

List<Class1> list= new List<Class1>();
//fill list...
List<Class1> aCopy=(List<Class1>) deepCopy(list);
Jeremy D
  • 4,787
  • 1
  • 31
  • 38
aLogic
  • 125
  • 1
  • 8
  • 1
    You can probably improve it by not trying to do it. If you absolutely must do a deep copy, implement it from scratch at the call site; trying to do it generically isn't feasible. – Louis Wasserman Apr 20 '13 at 18:06

1 Answers1

1

Instead of providing your own interface Deep for this, you could use java library's Cloneable. http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Cloneable.html

Most of the java classes already implement this interface.Like ArrayList etc.

Jaydeep Rajput
  • 3,605
  • 17
  • 35
  • 1
    I would suggest looking at [Cloning with generics](http://stackoverflow.com/questions/803971/cloning-with-generics), one of the thing they bring up is how `Cloneable` is a broken interface. – atomman Apr 20 '13 at 12:26