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

Java数组指定位置插入元素时右移逻辑错误问题排查

数组插入元素时右移逻辑错误修正

你的代码问题出在元素右移的循环方向:原代码从r+1开始向后遍历,会把r位置的元素不断向后复制,覆盖掉所有后续的原有元素,导致最终数组末尾全是重复值。

要解决这个问题,需要从数组的末尾向前遍历,把每个元素依次向后挪一位,这样才能保留原有的后续元素:

public void insertAtRank(int r, Object o) {
    // 从数组最后一位开始,向前到r+1的位置,逐个将元素后移
    for(int i = arrayVetor.length - 1; i > r; i-- ){
        arrayVetor[i] = arrayVetor[i-1];
    }
    this.arrayVetor[r] = o;
}

用这个修正后的方法执行你的测试代码:

arrayVetor.insertAtRank(0, "1");
arrayVetor.insertAtRank(1, "2");
arrayVetor.insertAtRank(2, "3");
arrayVetor.insertAtRank(3, "4");
arrayVetor.insertAtRank(2, "5");

最终数组输出会符合你的期望:[1, 2, 5, 3, 4, null, null, null, null, null]

内容的提问来源于stack exchange,提问作者Sózo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 13:50:39