Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep Cloning of Collections in java [closed]

Tags:

java

cloning

Recently I faced this question in an Interview:

Write a function to return a deep clone instance of class Drawing

public class Drawing{

  public List<Shape> shapes=new LinkedList<Shape>();

}

where shape is an abstract class having many concrete implementations

public abstract class Shape implements Serializable{

}

Can anyone please tell how to approach this?Do we need to add the clone method in all the concrete implementations?

like image 614
mahan07 Avatar asked Jul 16 '15 11:07

mahan07


1 Answers

What you need to do is first serialize the List<Shape> and then deserialize and return a new instance of Drawing with the deserialized List

public static Drawing deepClone(Drawing drawing) {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(drawing.shapes); //Serializes the drawing.shapes

        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bais); 
        return new Drawing((LinkedList<Shape>)ois.readObject()); //Deserializing and reading 
    } catch (IOException e) {
        return null;
    } catch (ClassNotFoundException e) {
        return null;
    }
}

Assuming you have a constructor in Drawing which takes in a LinkedList<Shape> as parameter

EDIT

You won't need to add clone() in Shape class as you override clone() method when you implement the Cloneable interface, but according to the question, they want you to create clones using Serializable interface.

like image 163
Sneh Avatar answered Oct 16 '22 09:10

Sneh