如何在AnyLogic的Main中获取不同类型智能体?代码问题求助
解决AnyLogic中遍历Atype/Btype智能体的问题
核心问题分析
你代码无法运行的原因有两个:
- 方法拼写错误:
get_Main()不是AnyLogic的正确写法,获取主代理的标准方法是getMain()(无下划线)。 - 集合引用错误:
getMain().Atype的写法不成立——Atype是智能体类,并非Main代理中的成员集合,不能直接通过类名引用实例。
两种可行解决方案
方案一:直接过滤所有行人中的目标类型(无需额外组件)
如果Atype和Btype是Pedestrian的子类,可通过主代理的行人集合筛选目标类型:
// 遍历所有Atype智能体 for(Pedestrian ped : getMain().getPedestrians()) { if(ped instanceof Atype) { Atype a = (Atype) ped; // 执行你的计算逻辑,例如调用a的属性/方法 } } // 遍历所有Btype智能体 for(Pedestrian ped : getMain().getPedestrians()) { if(ped instanceof Btype) { Btype b = (Btype) ped; // 执行你的计算逻辑 } }
方案二:用Population组件管理特定类型智能体(高效且易维护)
适合需要频繁遍历目标类型智能体的场景:
- 在Main代理中添加两个
Population组件,分别命名为atypeAgents(类型选择Atype)和btypeAgents(类型选择Btype)。 - 打开生成Atype的
PedSource,在On agent created事件中添加代码:atypeAgents.add((Atype) agent); - 打开生成Btype的
PedSource,在On agent created事件中添加代码:btypeAgents.add((Btype) agent); - 若智能体到达目的地后会销毁,需在Atype/Btype的On destroy事件中添加移除代码,避免空引用:
// Atype的On destroy事件 getMain().atypeAgents.remove(this);// Btype的On destroy事件 getMain().btypeAgents.remove(this); - 最后直接遍历Population集合:
for(Atype a : atypeAgents) { // 你的计算逻辑 } for(Btype b : btypeAgents) { // 你的计算逻辑 }
内容的提问来源于stack exchange,提问作者ruby zou
相关产品推荐
相关产品推荐

