Dart/Flutter中Map如何实现不存在则插入、已存在则商品计数自增?
问题原因
Dart中自定义类的实例默认相等判断基于内存引用,你创建的product1和product2虽然id、title属性完全一致,但属于两个不同的内存对象,因此HashMap的containsKey方法会判定为两个不同的键,才会出现重复新增条目的问题。
解决方案
这里提供两种可行方案,你可以根据业务场景选择:
方案1:重写Product类的==运算符和hashCode
通过重写类的相等判断逻辑,让HashMap可以识别属性相同的Product实例为同一个键:
class Product { final int id; final String title; Product({required this.id, required this.title}); // 重写相等判断逻辑,id和title都相等的Product实例判定为同一个对象 @override bool operator ==(Object other) => identical(this, other) || other is Product && runtimeType == other.runtimeType && id == other.id && title == other.title; // 重写hashCode,用属性的hash值组合生成 @override int get hashCode => id.hashCode ^ title.hashCode; }
修改后原有代码无需其他调整,运行即可得到期望的输出结果。
方案2:直接用商品唯一id作为HashMap的键
购物车场景下商品id本身就是全局唯一标识,直接用id做键可以避免重写类方法的成本,逻辑更简洁高效:
// HashMap的泛型调整为<int, int>,key存储商品id,value存储购买数量 final HashMap<int, int> hashMap = HashMap(); addToMap(Product product) { if (hashMap.containsKey(product.id)) { hashMap[product.id] += 1; } else { hashMap[product.id] = 1; } }
如果需要存储商品完整信息,可以额外维护一个id到Product实例的映射表,或者遍历统计结果时关联原商品数组读取属性即可。
内容的提问来源于stack exchange,提问作者TypeScript student
相关产品推荐
相关产品推荐

