NOTE: I have looked at different places including stackoverflow and have not found solution to this.
PROBLEM:
class Animal{
AnimalGroup animalGroup;
}
class AnimalGroup{
List<Animal> animalList;
}
class MainProgram{
// Map<groupRank, animalGroup>
Map<Integer, AnimalGroup> rankedAnimalGroups;
}
Note: As it is apparent one Animal can belong to only one AnimalGroup.
I want to deep copy the map rankedAnimalGroups.
Case1: Cloning
I will make my Animal and AnimalGroup Cloneable.
Clone method in AnimalGroup
protected Object clone() throws CloneNotSupportedException {
AnimalGroup clonedAnimalGroup = (AnimalGroup)super.clone();
for(Animal animal: animalList)
clonedAnimalGroup.addAnimal(animal.clone);
return clonedAnimalGroup;
}
Clone method in Animal
protected Object clone() throws CloneNotSupportedException {
Animal clonedAnimal = (Animal)super.clone();
clonedAnimal.animalGroup = animalGroup.clone();
}
This will end up in a cycle of AnimalGroup calling Animal and reverse.
Case2: copyConstructor
HashMap doesnot support deep copy constructor
Suggested Solution
I can use constructor for Animal, inside clone method of AnimalGroup, as follows
Clone method in AnimalGroup
protected Object clone() throws CloneNotSupportedException {
AnimalGroup clonedAnimalGroup = (AnimalGroup)super.clone();
for(Animal animal: animalList)
clonedAnimalGroup.addAnimal(new Animal(animal, this));
return clonedAnimalGroup;
}
Constructor in Animal
public Animal(Animal other, AnimalGroup animalGroup)
{
this.animalGroup = animalGroup;
...
}
Question Is there any better solution for deep copy in such case.
Edit1
Data size is too large for serialization related approach.
Edit2
I can not include external libs etc for copying in my project