I am working with an agent-based simulation of an infectious disease epidemic in AnyLogic. I have two agents types in my model- Person and Building. I'm trying to write a function that counts the number of infectious contacts that the agent type 'Person' has at any given point in time. Below is my code for the function:
int infectedConnections = 0;
if (getConnections() != null)
for (Agent a : this.getConnections())
{
Person p = (Person) a;
if (p.IsCurrentlyInfected())
infectedConnections++;
}
return infectedConnections ;
The code compiles without any errors but during runtime, it throws up a java.lang.ClassCastException with the message: model.Building cannot be cast to model.Person.
When I try the same code with just one agent type (i.e. 'Person'), the model runs fine and the function returns the correct value. Could someone tell me how I could rectify my code so that I am able to run the function for 'Person' please?
If you just want to ignore agents of type Building, then you can do the following:
int infectedConnections = 0;
if (getConnections() != null) {
for (Agent a : this.getConnections())
{
if(a instanceof Person) {
Person p = (Person) a;
if (p.IsCurrentlyInfected()) {
infectedConnections++;
}
}
}
}
return infectedConnections;
The problem is that (Person) a;
will fail if a
is a Building instead of a Person.