Reputation: 3500
I understand how to do a java deep copy using Serializable and Streams but as long as the object to copy has only primitive data types. In my case I have a parent class that contains among primitive data types an ArrayList of a child class, and they also need to be deep copied.
Can someone please point me to the right direction to do it?
UPDATE:
I thought it was working but I just realize it is not.
This is what I have.
public class Pack implements Serializable
{
String ID;
String serviceCode;
String name;
String type;
ArrayList<Service> services;
public Pack deepClone()
{
try
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(this);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
Pack clone = (Pack) ois.readObject();
clone.setID(null);
clone.setType("Replica");
return clone;
}
catch (IOException e)
{
return null;
}
catch (ClassNotFoundException e)
{
return null;
}
}
}
public class Service implements Serializable
{
String ID;
String serviceCode;
String name;
}
Now after cloning a Parent class a get a nice clone but the services array is null.
UPDATE:
Sorry my mistake, it was the lack of sleep. It is indeed working.
Upvotes: 3
Views: 300
Reputation: 918
Just need to make sure the object of that array list also implements serializable, ie your child class
Upvotes: 2
Reputation: 8928
Serialization is done no matter either you have primitive data types or not. The only condition is that your child classes need to be serializable too.
Refer here for a quick tutorial java_serialization
Upvotes: 4