AnyLogic中LinkedList无法移除队列订单对应元素的问题求助
问题根源与解决方法
你的问题核心在于Java对象的默认相等性判断逻辑:你每次在进入/退出事件中new ExportInfo(...)都会创建一个全新的对象实例,哪怕属性值完全一致,它们在内存中的引用地址也是不同的。LinkedList的remove(Object o)方法默认用equals()比较对象引用,因此无法匹配到列表中已存在的元素,自然无法移除。
下面是三种可行的解决方式:
方法一:重写ExportInfo的equals和hashCode方法
让类根据订单ID(唯一标识)来判断对象是否相等,这样即使是新创建的对象,只要ID匹配就能被识别。
修改你的ExportInfo类:
import java.util.Objects; class ExportInfo { private int id; private int P; private double d; public ExportInfo(int id, int P, double d) { this.id=id; this.P=P; this.d=d; } // 根据订单ID判断对象相等 @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ExportInfo that = (ExportInfo) o; return id == that.id; } // 与equals逻辑保持一致,避免哈希表相关问题 @Override public int hashCode() { return Objects.hash(id); } }
修改后,你原来的退出事件代码就能正常工作,因为新创建的ExportInfo会通过ID匹配到列表中的对应元素。
方法二:将ExportInfo实例关联到Agent
直接把创建的ExportInfo存到Agent的属性中,退出时直接移除这个关联的实例,无需依赖相等性判断。
- 在你的Agent类型中添加属性:
ExportInfo exportInfo - 队列进入事件代码:
agent.exportInfo = new ExportInfo(agent.atrID, agent.atrEstimatedPackingTime, dateToTime(agent.atrDueDate)); list.add(agent.exportInfo);
- 队列退出事件代码:
list.remove(agent.exportInfo);
这种方式最直接,完全避免了对象相等性的问题,同时减少了重复对象的创建。
方法三:遍历列表匹配ID移除
如果不想修改类或Agent属性,可以直接遍历LinkedList,找到ID匹配的元素后移除:
首先给ExportInfo添加获取ID的方法:
class ExportInfo { // ...原有代码 public int getId() { return id; } }
然后修改队列退出事件代码:
Iterator<ExportInfo> iterator = list.iterator(); while (iterator.hasNext()) { ExportInfo info = iterator.next(); if (info.getId() == agent.atrID) { iterator.remove(); break; // 订单ID唯一,找到后直接退出循环 } }
内容的提问来源于stack exchange,提问作者Marloes
相关产品推荐
相关产品推荐

