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

如何更新ArrayList中数组的元素及内部数组的元素?

嘿,这问题我熟!咱们分两种情况来拆解,一步步给你讲明白怎么操作~

一、更新ArrayList中指定位置的整个数组

如果你想直接把ArrayList里某一个位置的数组替换成全新的数组,用ArrayList.set(int index, E element)方法就搞定了。这个方法会把指定索引位置的元素替换成你传入的新数组,同时还会返回原来的那个数组(如果需要保留旧数据的话可以用变量接住)。

举个简单的例子:

// 先创建一个存int数组的ArrayList
ArrayList<int[]> myList = new ArrayList<>();
myList.add(new int[]{1,2,3});
myList.add(new int[]{4,5,6});

// 把索引1的数组替换成新数组{7,8,9}
myList.set(1, new int[]{7,8,9});

⚠️ 注意:一定要确保你用的索引在合法范围内——也就是从0到myList.size()-1,不然会直接抛出IndexOutOfBoundsException异常哦!

二、更新内部数组的单个元素

如果只是想修改ArrayList里某个数组中的某一个元素,步骤分两步:

  1. 先用ArrayList.get(int index)取出目标数组;
  2. 直接修改这个数组的指定索引元素就行。

因为数组是引用类型,你取出的数组和ArrayList里存的是同一个对象,所以修改后ArrayList里的数组会自动同步变化,不用再调用set方法存回去~

举个例子:

// 接上面的myList,取出索引0的数组
int[] targetArray = myList.get(0);
// 修改这个数组的第2个元素(索引是1)
targetArray[1] = 99;

这时候myList里第一个数组就变成了{1,99,3}啦!

完整代码示例

把两种操作放在一起,看个完整的运行效果:

import java.util.ArrayList;

public class UpdateArrayListOfArrays {
    public static void main(String[] args) {
        ArrayList<int[]> numberLists = new ArrayList<>();
        numberLists.add(new int[]{10, 20, 30});
        numberLists.add(new int[]{40, 50, 60});
        numberLists.add(new int[]{70, 80, 90});

        // 操作1:替换整个数组
        numberLists.set(1, new int[]{400, 500, 600});
        System.out.println("替换索引1后的数组列表:");
        printArrayList(numberLists);

        // 操作2:修改数组内部元素
        int[] firstArray = numberLists.get(0);
        firstArray[0] = 1000;
        System.out.println("\n修改第一个数组后的数组列表:");
        printArrayList(numberLists);
    }

    // 辅助打印方法
    private static void printArrayList(ArrayList<int[]> list) {
        for (int[] arr : list) {
            for (int num : arr) {
                System.out.print(num + " ");
            }
            System.out.println();
        }
    }
}

运行后输出:

替换索引1后的数组列表:
10 20 30 
400 500 600 
70 80 90 

修改第一个数组后的数组列表:
1000 20 30 
400 500 600 
70 80 90 
额外注意点
  • 不管是get还是set,索引都不能越界,操作前可以先判断:if (index >=0 && index < myList.size())
  • 如果你的ArrayList里存的是包装类型数组(比如Integer[]),操作逻辑完全一样,直接修改对应索引的元素就行
  • 如果你担心误修改原数组,可以取出数组后复制一份再修改,但这种场景比较少,按需选择就好

内容的提问来源于stack exchange,提问作者M A SH

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:54:00