Java学习,List 元素替换

Java中List接口,提供了多种方法来替换元素,可以通过索引,访问和替换List中的元素。

示例:

public class ListElementReplacementExample {

public static void main (String\[\] args) {

// 创建ArrayList

List<String> list = new ArrayList<>();

list.add("Apple");

list.add("Banana");

list.add("Cherry");

// 打印原始列表

System.out.println("Original List: " + list);

// 通过索引替换元素

// 将索引为1的元素(Banana)替换为Orange

list.set(1, "Orange");

// 打印替换后的列表

System.out.println("List after replacement: " + list);

}

}

Collections 类的 replaceAll() 替换List中所有的指定元素:

import java.util.*;

public class Main {

public static void main (String\[\] args) {

List list = Arrays.asList("one Two three Four five six one three Four".split(" "));

System.out.println("List :"+list);

Collections.replaceAll(list, "one", "hundrea");

System.out.println("replaceAll: " + list);

}

}

相关推荐
BK贝壳5 小时前
bool-hybrid-array 的 GPU_opt 与 cjx:一个没显卡就报错的开关,一个把 800 字压到 96 字节的编码
python
多加点辣也没关系8 小时前
JavaScript|第41章:性能优化实战
开发语言·javascript·性能优化
BD_Marathon9 小时前
安装Jupyter notebook
ide·python·jupyter
Zlzxzw9 小时前
End-to-End Autonomous Generation of Human Assembly Plans
python
Resean02239 小时前
架构设计系列(十六):DDD 与代码架构
java·开发语言·架构
Wellijohn9 小时前
2000 个请求、30% 失败率:我把 Python 批量并发的限流和重试参数算了一遍
后端·python·性能优化
学长毕设10 小时前
基于SpringBoot 车辆租赁系统平台-附源码
java·spring boot·后端
码途行者10 小时前
每天10分钟学Go:第22课 自定义错误
开发语言·后端·golang
23图10 小时前
C 语言开散列表(拉链法)拆解:链挂得没错,key=-1 会去读 T[-1]
c语言·开发语言·散列表
feixing_fx11 小时前
解构与展开:可读性和性能的取舍
开发语言·前端·javascript·前端框架