I've came across a problem that I have 2 objects as the fields of each other. I'll give a simplistic example:
public class Dog{
boolean tired;
Walk walk;
public boolean setTired(boolean tired){
this.tired = tired;
}
}
public class Walk implements Runnable{
int seconds;
Dog dog;
public void run(){
//After conditions are met
dog.setTired(true);
}
public int getSeconds(){
return seconds;
}
}
I'm saving Dog
instances to a HashSet and by that I can get the Walk
instances.
Walk
is essentialy a class which helps Dog
but it's in a different class because i need it to return stuff so I don't want it to be an anonymous Runnable.
Here comes the problem - I want to serialize the Dog
HashSet and save it into a file, but I can't do that, I get these long repeating errors until I get a StackOverFlow error.
I searched it online and saw that because I have Walk
as a field in Dog
and Dog
as a field in Walk
, it goes into an infinite loop from what I gathered.
I thought about looping through the HashSet inside the Runnable and check if the Dog
's Walk
field is equal to this Walk
class, but, I have a condition which would need to run the loop every time the Runnable executes, so I'm guessing it would reduce the performance a lot for such a simple task.
Does anyone have an alternative solution or has an advice on what I should do in order to serialize the class?