You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中DerivedProduct类存储组成产品及对应数量的适用数据结构选型

适配需求的可选数据结构方案

以下是三种最常用的实现方式,可根据你的业务场景选择:

方案1:自定义实体类 + ArrayList 存储

  • 先定义独立的ComponentEntry类,内部仅包含两个成员:Product类型的组成产品实例、int类型的对应数量,再给DerivedProduct新增一个ArrayList<ComponentEntry>类型的属性即可。
  • 优势:支持按顺序存储组成产品,允许重复添加同一种Product(如果业务有这类特殊需求),遍历、修改元素的逻辑直观易维护。
    参考代码结构:
// 自定义组成条目类
class ComponentEntry {
    private Product product;
    private int quantity;

    public ComponentEntry(Product product, int quantity) {
        this.product = product;
        this.quantity = quantity;
    }
    // 按需补充getter、setter方法
}

// DerivedProduct内部的属性定义
private List<ComponentEntry> components = new ArrayList<>();

方案2:直接使用Map存储

  • 给DerivedProduct新增Map<Product, Integer>类型的属性,Key存储组成的Product对象,Value存储对应的数量。
  • 优势:不需要额外定义新类,天然对组成Product去重,查询某类Product的数量时间复杂度为O(1)。注意要提前给Product类重写equals()和hashCode()方法,保证Map对Key的判定符合你的业务规则。
    参考代码结构:
// DerivedProduct内部的属性定义
private Map<Product, Integer> componentMap = new HashMap<>();

方案3:Record简化实现(Java 16+支持)

如果使用Java 16及以上版本,可以用Record简化自定义类的写法,不需要手动编写构造、getter等冗余代码,再配合ArrayList存储即可,是方案1的轻量化版本:

// 一行代码定义组合条目
record ComponentEntry(Product product, int quantity) {}

// DerivedProduct内部的属性定义
private List<ComponentEntry> components = new ArrayList<>();

内容的提问来源于stack exchange,提问作者iugubhk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 14:09:03