CopyOnWriteArrayList类的set()方法用于将列表中指定位置的元素替换为指定的元素。它返回被替换的元素。
语法如下
public E set(int index, E ele)
此处,参数index是要替换的元素的索引,而ele是要存储在指定位置的元素。
要使用CopyOnWriteArrayList类,您需要导入以下包
import java.util.concurrent.CopyOnWriteArrayList;
以下是在Java中实现CopyOnWriteArrayList类set()方法的示例
import java.util.concurrent.CopyOnWriteArrayList; public class Demo { public static void main(String[] args) { CopyOnWriteArrayList<Integer> arrList = new CopyOnWriteArrayList<Integer>(); arrList.add(30); arrList.add(40); arrList.add(60); arrList.add(70); arrList.add(90); arrList.add(100); arrList.add(120); System.out.println("CopyOnWriteArrayList = " + arrList); System.out.println("Replaced element = " + arrList.set(3, 50 )); System.out.println("Updated CopyOnWriteArrayList = "+arrList); } }
输出结果
CopyOnWriteArrayList = [30, 40, 60, 70, 90, 100, 120] Replaced element = 70 Updated CopyOnWriteArrayList = [30, 40, 60, 50, 90, 100, 120]