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

}

}

相关推荐
科雷软件测试1 小时前
Python中itertools.product:快速生成笛卡尔积
开发语言·python
OOJO2 小时前
c++---list介绍
c语言·开发语言·数据结构·c++·算法·list
雨白2 小时前
深入理解 Kotlin 协程 (二):万剑归宗,揭秘 Kotlin 协程的精妙取舍
kotlin
程序员陆业聪3 小时前
你的 Android App 可能白白损失了 35% 的性能——R8 全模式配置详解
android
派大星~课堂4 小时前
【力扣-142. 环形链表2 ✨】Python笔记
python·leetcode·链表
Thomas.Sir4 小时前
第一章:Agent智能体开发实战之【初步认识 LlamaIndex:从入门到实操】
人工智能·python·ai·检索增强·llama·llamaindex
笨笨饿4 小时前
29_Z变换在工程中的实际意义
c语言·开发语言·人工智能·单片机·mcu·算法·机器人
Amazing_Cacao4 小时前
深度观察 | 从“产区玄学”到“液态战场”:精品巧克力的终极试金石
学习
艾为电子4 小时前
【技术帖】让接口不再短命:艾为 C-Shielding™ Type-C智能水汽防护技术解析
c语言·开发语言
ZTL-NPU4 小时前
Jetbrains开发ros
ide·python·pycharm·编辑器·ros·clion