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

}

}

相关推荐
清水白石0085 小时前
Python 编程实战全景:从基础语法到插件架构、异步性能与工程最佳实践
开发语言·python·架构
lwf0061645 小时前
导数学习日记
学习·算法·机器学习
鹏晨互联5 小时前
《Android 自定义 WebView 组件:从封装到路由,打造灵活可复用的混合开发利器》
android
yaoxin5211235 小时前
390. Java IO API - WatchDir 示例
java·前端·python
qeen876 小时前
【编程日记】现阶段总结
学习
程序员陆业聪6 小时前
AI Code Review:让每一行代码都有AI审查员
android
程序员陆业聪6 小时前
AI Bug修复与测试生成:从崩溃日志到修复PR的自动化 | AI提效Android开发(5)
android
诸神黄昏EX6 小时前
Android Google Widevine
android
武帝为此6 小时前
【数据清洗缺失值处理】
python·算法·数学建模
zhangchaoxies7 小时前
如何在 Go 中安全复制接口指针所指向的值
jvm·数据库·python