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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With