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 小时前
深入解析 Android Performance Analyzer (APA) 底层架构与技术原理
android
吃饱了得干活8 小时前
Spring Cloud Gateway 微服务网关:路由、断言、过滤器
java·spring cloud
Warson_L9 小时前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅9 小时前
海天线算法的前世今生
python·计算机视觉
韩师傅9 小时前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L9 小时前
LangGraph的MessageState and HumanMessage
python
韩师傅9 小时前
当你的甲方吐槽天空不够蓝,你应该如何应对
python·计算机视觉
李斯维9 小时前
从历史的角度看 Android 软件架构
android·架构·android jetpack
lwx5728010 小时前
探秘InnoDB:搞懂它的内存、线程、磁盘与日志刷盘策略
java·后端
Warson_L10 小时前
python的类&继承
python