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

}

}

相关推荐
用户835629078051几秒前
使用 Python 合并 PowerPoint 演示文稿
后端·python
xh didida2 分钟前
Linux -- 基础IO
linux·服务器·开发语言·c++
小雪崩8 分钟前
嵌入式学习 day64:字符设备驱动
学习
weixin_4617694014 分钟前
VS Code 中创建 Jupyter 文件(.ipynb)
ide·python·jupyter
个 人 练 习 生21 分钟前
C++ string 类模拟实现:从底层理解字符串(上)
开发语言·c++·经验分享·学习·程序人生
2601_9669496530 分钟前
多市场量化策略的数据接口应该如何设计:从数据层架构到策略接入
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
坤坤子吖33 分钟前
C++智能指针:RAII、shared_ptr与内存泄漏
开发语言·c++·笔记·学习
浪潮IT馆35 分钟前
Android Studio 非最新版本下载安装教程
android·ide·android studio
全栈弄潮儿39 分钟前
Python实战第1期:Python环境搭建与第一个程序
python
奋斗的阿狸_198643 分钟前
ESP32-S3 + ES7210 四通道麦克风录音上传方案
c语言·开发语言·fpga开发