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

Java Song类catenation拼接方法无法实现Note数组复制问题求助

问题核心原因

你目前的代码遗漏了两个核心逻辑:

  1. 没有访问Song类私有成员data、manyItems的入口,无法读取两个入参Song的音符数据,也无法给新生成的Song写入拼接后的结果
  2. 完全没有实现两个入参Song的Note数组元素复制、新Song有效元素计数的赋值逻辑
具体修复步骤

1. 给Song类补充必要的访问方法

因为data、manyItems是私有属性,外部静态方法无法直接访问,需要在Song类中添加对应的getter/setter:

class Song {
    // 原有代码保持不变
    // 新增以下方法
    public Note[] getData() {
        return data;
    }
    public int getManyItems() {
        return manyItems;
    }
    public void setData(Note[] newData) {
        this.data = newData;
    }
    public void setManyItems(int count) {
        if (count < 0) throw new IllegalArgumentException("count can not be negative");
        this.manyItems = count;
    }
}

2. 完善catenation方法的数组复制逻辑

public static Song catenation(Song s1, Song s2){
    if (s1 == null || s2 == null) throw new NullPointerException("arguments are null");
    
    String newName = s1.getName() + " and " + s2.getName();
    int newBpm = (s1.getBPM() + s2.getBPM()) / 2;
    // 提前判断bpm合法性,避免创建Song时抛异常
    if (newBpm > Song.MAX_BPM || newBpm < Song.MIN_BPM) {
        throw new IllegalArgumentException("calculated bpm is out of valid range");
    }
    Song res = new Song(newName, newBpm);

    // 计算总元素数量
    int totalNotes = s1.getManyItems() + s2.getManyItems();
    // 如果新数组需要的容量超过Song初始化的默认容量,先扩容
    if (totalNotes > res.getData().length) {
        res.setData(new Note[totalNotes]);
    }
    // 复制s1的所有有效音符
    System.arraycopy(s1.getData(), 0, res.getData(), 0, s1.getManyItems());
    // 复制s2的所有有效音符,接在s1的元素后面
    System.arraycopy(s2.getData(), 0, res.getData(), s1.getManyItems(), s2.getManyItems());
    // 给新Song设置正确的有效元素计数
    res.setManyItems(totalNotes);

    return res;
}
补充说明
  • 上面的实现用的是浅拷贝,如果你需要修改拼接后的Song的音符不影响原s1、s2,可以遍历每个Note对象做深拷贝后再存入新数组
  • 如果你不需要对外暴露data数组的完整访问权限,也可以在Song类中封装addNotes(Note[] notes, int count)方法,在方法内部完成元素添加逻辑,封装性更好

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 12:57:03