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.