有没有一种简单的方法可以从超类对象列表中创建子类对象列表?

时间:2018-12-13 01:28:15

标签: java repast-simphony

我有一组Agent对象(超类)。

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

public class Healthy extends Agent

public class Infected extends Agent

每个Agent x对象都会保留与Agent x接触过的所有Agent 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


            }
         }
      }

是否有一种简单的方法可以遍历Agent y对象的列表,并将所有Healthy的Agent排序到一个名为Healthyy的新列表“ healthy_links”中?

1 个答案:

答案 0 :(得分:2)

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