如何统计utilities集合中指定特征Agent并解决类转换异常
问题根因
count()函数遍历容器列表时,lambda表达式的形参p代表列表内的单个遍历元素,你代码里错误地将整个agent.contents()列表对象(类型为Collections$UnmodifiableList)强转为AgentA类型,和实际类型不匹配,因此抛出ClassCastException。
修复方案
将lambda谓词中强转的对象从agent.contents()替换为遍历形参p即可。
修正后的统计表达式:
count(agentB.contents(), p -> ((AgentA)p).DeliveryPoint == agentB.DeliveryPoint)
对应给出的代码块,修正后完整实现:
private void _movingToDeliveryPoint_onExit_xjal( final com.anylogic.libraries.processmodeling.Delay<AgentB> self, AgentB agent ) { traceln(count(agent.contents(), p -> ((AgentA)p).DeliveryPoint == agent.DeliveryPoint)); }
可选优化
如果AgentB容器内可能存在非AgentA类型的其他对象,可以在判断条件前增加类型校验,避免后续运行时出现类型转换错误:
count(agent.contents(), p -> p instanceof AgentA && ((AgentA)p).DeliveryPoint == agent.DeliveryPoint)
内容的提问来源于stack exchange,提问作者dkdelta
相关产品推荐
相关产品推荐

