1

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?

Taylor Marie
  • 357
  • 1
  • 15
  • 1
    A `Stream` (since JDK 8) should help. Ask the list for a `stream()`, `filter()` items using `instanceof`, make them `toArray()` and back `Arrays.asList()`. – Michael Butscher Dec 13 '18 at 01:47

1 Answers1

2
if (a instanceof HealthyAgent) {
    this.healthy_links.add((HealthyAgent)a);
}
nemanja228
  • 556
  • 2
  • 16
  • Thanks! This worked and was the simple solution I was looking for, but I should note that it required that I cast a. For example ...this.healthy_links.add(Healthy(a)); – Taylor Marie Dec 13 '18 at 17:51
  • @TaylorMarie, sorry I spend 90% of my programming time working with C# where you can do `if (a is HealthyAgent castedA) { this.healthy_links.add(castedA) }` Glad that I could help :) – nemanja228 Dec 13 '18 at 18:05