Java ArrayList.set() 方法及代码示例
修改指定索引位置的元素为指定对象
定义
public E set(int index, E element)
参数
参数类型 | 参数名称 | 参数描述 |
---|---|---|
int | index | 要修改的索引的位置 |
E | element | 要设置的元素 |
类型参数 | E | 数组列表元素的类型 |
返回值
返回在指定索引位置被设置前的元素
抛出的异常
IndexOutOfBoundsException
如果索引超出范围 (index < 0 || index >= size())
说明
本方法方法由 List<E>
接口的 set()
方法指派
本方法重写了继承自 AbstractCollection<E>
类的 set()
方法
示例
设置数组列表元素的示例
package com.yi21.arraylist; import java.util.ArrayList; public class Yi21ArraysListSet { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Hello"); list.add("World"); list.add("World"); list.add("21yi"); System.out.println("设置第一个 World 为 世界: " + list.set(1, "世界")); System.out.println("设置第二个 World 为 ShiJie: " + list.set(2, "ShiJie")); System.out.println("列表内容:"); list.forEach(System.out::println); } }
执行结果为 :
设置第一个 World 为 世界: World 设置第二个 World 为 ShiJie: World 列表内容: Hello 世界 ShiJie 21yi