Java POS项目点击按钮向LinkedList添加带构造函数对象失效求助
问题排查及修复方案
1. ProductInfo构造函数逻辑错误
你当前的ProductInfo构造函数中,成员变量quantity没有传入参数就直接赋值,属于无效操作:
// 原错误代码 public ProductInfo(String productName, int productID, String variant, char size, double unitPrice){ this.productName = productName; this.productID = productID; this.variant = variant; this.size = size; this.unitPrice = unitPrice; this.quantity = quantity; // 这里的quantity就是当前未初始化的成员变量,等于给自身赋值,没有实际效果 }
修复方案:
要么在构造函数参数中增加quantity参数传入,要么给quantity设置默认初始值:
// 修复示例1:设置默认初始值,点击一次按钮默认加1份 public ProductInfo(String productName, int productID, String variant, char size, double unitPrice){ this.productName = productName; this.productID = productID; this.variant = variant; this.size = size; this.unitPrice = unitPrice; this.quantity = 1; } // 修复示例2:新增quantity入参,灵活指定添加数量 public ProductInfo(String productName, int productID, String variant, char size, double unitPrice, int quantity){ this.productName = productName; this.productID = productID; this.variant = variant; this.size = size; this.unitPrice = unitPrice; this.quantity = quantity; }
2. Handler类预创建迭代器的冗余/异常风险
你在Handler类中把迭代器作为成员变量提前初始化,Java的集合迭代器是快照式的,后续往列表添加元素后,这个旧迭代器不会同步更新,后续如果用到这个迭代器会直接抛出ConcurrentModificationException异常,即使当前没用到也属于无效冗余代码。
修复方案:删除这行成员变量声明,需要迭代遍历的时候再临时创建迭代器即可。
另外你当前的tick方法用索引遍历LinkedList效率很低,LinkedList是链表结构,随机访问时间复杂度为O(n),可以改成增强for循环优化:
public void tick(){ for(ProductInfo tempProduct : productList){ tempProduct.tick(); } }
3. Handler类删除方法拼写错误
removeProdcut拼写错误,少了字母t,正确拼写为removeProduct,后续调用该方法时会找不到对应方法导致报错。
4. 确认Handler实例全局唯一
如果以上问题修复后还是无法添加成功,大概率是你在按钮监听器中使用的handler实例,和你后续读取产品列表的handler不是同一个实例,每次点击添加的元素都存到了另一个Handler对象的列表里,自然看不到效果。
修复方案:全局共用同一个Handler实例,比如将Handler设置为单例,或者在界面初始化时创建一次Handler实例,所有逻辑都复用这个实例即可。
内容的提问来源于stack exchange,提问作者Vince Viloria
相关产品推荐
相关产品推荐

