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

Java中ArrayList替代数组animal[i]=animal[i+1]的等效操作是什么?

数组赋值操作对应的ArrayList写法解析

嘿,这问题挺典型的,我来给你掰扯清楚!

首先你得明白为啥animal.get(i) = animal.get(i+1)会报错——get()方法只是返回ArrayList中对应索引的元素值,它不是一个可以被赋值的"变量",就像你不能写5 = 10一样,左边得是个能接收值的目标才行。

而数组里的animal[i] = animal[i+1]本质是把索引i+1位置的元素值,覆盖到索引i的位置上。对应ArrayList的等效操作,得用它的set()方法:

animal.set(i, animal.get(i+1));

这里set(int index, E element)方法的作用就是:把ArrayList中指定index位置的元素,替换成传入的element值。刚好对应数组里直接给索引位置赋值的逻辑。

举个简单的例子直观感受下:

import java.util.ArrayList;

public class Test {
    public static void main(String[] args) {
        ArrayList<String> animals = new ArrayList<>();
        animals.add("猫");
        animals.add("狗");
        animals.add("兔子");
        
        // 对应数组的 animals[0] = animals[1]
        animals.set(0, animals.get(1));
        
        System.out.println(animals); // 输出: [狗, 狗, 兔子]
    }
}

简单总结下:数组是直接通过索引访问内存位置赋值,而ArrayList作为封装类,需要用set()方法来修改指定索引的元素,get()只能用来读取~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:34:21