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

}

}

相关推荐
小小测试开发3 小时前
安装 Python 3.10+
开发语言·人工智能·python
梦想不只是梦与想4 小时前
Python 中的装饰器
python·装饰器
我叫唧唧波4 小时前
Python+AI 全栈学习笔记
人工智能·python·学习
故渊at5 小时前
系列三:组件化与模块化进阶 | 第11篇 组件化项目规范与问题根治:依赖、资源、Manifest 与混淆的全链路管控
android·架构·mvvm·模块化·组件化
故渊at5 小时前
系列二:MVVM 深度实战与项目重构 | 第7篇 LiveData & StateFlow 状态管理实战:从“粘包弹”到“丝滑流式”
android·重构
AAA大运重卡何师傅(专跑国道)5 小时前
【无标题】
开发语言·c#
copyer_xyf5 小时前
Python 异常处理
前端·后端·python
是阿建吖!5 小时前
【Linux】信号
android·linux·c语言·c++
城北徐宫5 小时前
Linux信号深度解剖:5种产生、3张表、4次切换
linux·c++·学习
XBodhi.5 小时前
Visual Studio C++ 语法错误: 缺少“;”(在“return”的前面)
开发语言·c++·visual studio