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

}

}

相关推荐
江畔柳前堤2 分钟前
github实战指南03-Pull Request 全流程实战
开发语言·人工智能·python·深度学习·github·word
森G4 分钟前
67、Qt 多媒体框架概述---------多媒体
开发语言·qt
小风吹啊吹~8 分钟前
通过时态图学习意图驱动识别足球控球比赛阶段 论文详解
学习·transformer·论文笔记·gan·足球战术·战术分析系统
2501_9159184113 分钟前
iOS App性能测试工具的实现方法与优化循环指南
android·ios·小程序·https·uni-app·iphone·webview
葛兰岱尔14 分钟前
从 SolidWorks 到 Three.js,从 Inventor 到 Unity——制造业CAD模型“几何-语义一体化“转换,不再是天方夜谭!
开发语言·javascript·unity
小小晓.18 分钟前
零基础C++小白突破
开发语言·c++
何以解忧,唯有..21 分钟前
Go语言类型转换详解:从基础到进阶实践
开发语言·后端·golang
何以解忧,唯有..25 分钟前
Go 语言指针类型详解:从基础到实战
开发语言·后端·golang
阿i索26 分钟前
【C++学习笔记】【基础】4.string类(2)——模拟实现
c++·笔记·学习