1

我有一组代理对象(超类)。

代理对象可以是:1)受感染(扩展代理)和 2)健康(扩展代理)。例子...

public class Healthy extends Agent

public class Infected extends Agent

每个代理 x 对象都保存一个列表,其中列出了与代理 x 接触的所有代理 y 对象,无论子类如何。列表的类型是 Agent,这个列表是一个名为“links”的实例变量。例子...

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


            }
         }
      }

有没有一种简单的方法可以遍历代理 y 对象列表并将所有健康的代理分类到一个名为“healthy_links”的新列表中,类型为健康?

4

1 回答 1

2
if (a instanceof HealthyAgent) {
    this.healthy_links.add((HealthyAgent)a);
}
于 2018-12-13T01:42:02.980 回答