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);

}

}

相关推荐
05候补工程师3 小时前
【Python实战】告别杂乱脚本!基于SOLID原则与策略模式的 PDF转Word 批量处理系统
python·设计模式·pdf·word·策略模式
Biomamba生信基地3 小时前
拷贝数变异分析的python实现及R语言对比
python·r语言·生物信息学·单细胞测序
朝新_3 小时前
【LangChain】少样本提示(few-shorting) 掌握 Few-Shot 提示,让大模型按你的规则输出
java·人工智能·langchain
Le_ee3 小时前
ctfweb:flask+ssti
后端·python·flask
duke8692672143 小时前
html怎么用inert属性禁用_HTML如何通过Inert暂停交互区域
jvm·数据库·python
xyq20243 小时前
Swift 类
开发语言
赏金术士3 小时前
Kotlin 从入门到进阶 之异常与标准库(八)
android·开发语言·kotlin
万能菜道人3 小时前
LVGL9.5版本的基础使用学习
学习
Brilliantwxx3 小时前
【C++】认识 list(初步认识+模拟实现)
开发语言·数据结构·c++·笔记·算法·list
七七powerful3 小时前
mac电脑安装cmca根证书
java·前端·macos