Search code examples
javarepast-simphony

Is there a simple way to create a list of subclass objects from a list of the superclass objects?


I have a set of Agent objects (the superclass).

Agent objects can be: 1) Infected (extents Agent) and 2) Healthy (extends Agent). Example...

public class Healthy extends Agent

public class Infected extends Agent

Each Agent x object keeps a list of all the Agent y objects that have come into contact with Agent x, regardless of the subclass. The type of the list is Agent and this list is an instance variable named "links". Example...

public class Agent {
    protected Context<Object> context;
    protected Geography<Object> geog;
    private int Id;
    public Coordinate location;
    public ArrayList<Agent> links = new ArrayList<>();
    public ArrayList<Healthy> healthy_links = new ArrayList<>();

    public Agent(Context<Object> context, Geography<Object> geog) {
        this.context = context;
        this.geog = geog;
        this.Id = Id;
        this.location = location;
        this.links = links;
        this.healthy_links = healthy_links;
    }
}
//getters and setters

    public void findContacts(){
        Context context = ContextUtils.getContext(this);
        //create a list of all agents
        IndexedIterable<Agent> agents = context.getObjects(Agent.class);
        for(Agent a: agents){
            //if any of the agents are in the same location as this, if the links list doesnt already contain the agent, and if the agent is not this, then add it to the links list
            if(a.getLocation()== this.getLocation() && !this.links.contains(a) && this != a){

                this.links.add(a); //this is obviously possible//

                this.healthy_links.add(a); //this is obviously not possible, but is there a super simple alternative


            }
         }
      }

Is there a simple way to go through the list of Agent y objects and sort all the Agents that are Healthy into a new list called "healthy_links" of type Healthy?


Solution

  • if (a instanceof HealthyAgent) {
        this.healthy_links.add((HealthyAgent)a);
    }