Java List 中的 set(int index, E element) 方法详解
set(int index, E element) 方法用于替换指定索引位置的元素,并返回被替换的元素。
具体作用是将指定位置的元素替换为新的元素,并返回替换前的元素。可以用于更新列表中指定位置的元素。
例如,以下代码将列表中索引为 1 的元素替换为 'world',并返回被替换的元素 'hello':
List<String> list = new ArrayList<>(Arrays.asList('hello', 'world', 'java'));
String replacedElement = list.set(1, 'world');
System.out.println(replacedElement); // 输出 'hello'
使用方法:
- index: 要替换元素的索引位置。
- element: 要替换的元素。
返回值:
- 返回被替换的元素。
注意:
- 索引位置必须在列表的有效范围内,否则会抛出 IndexOutOfBoundsException 异常。
- 如果要替换的元素类型与列表中现有元素类型不一致,则会抛出 ClassCastException 异常。
示例代码:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SetMethodExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList('hello', 'world', 'java'));
// 替换索引为 1 的元素
String replacedElement = list.set(1, 'world');
System.out.println('Replaced element: ' + replacedElement); // 输出 'Replaced element: hello'
// 打印更新后的列表
System.out.println(list); // 输出 [hello, world, java]
}
}
原文地址: http://www.cveoy.top/t/topic/bOxW 著作权归作者所有。请勿转载和采集!