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

}

}

相关推荐
玩机达人887 分钟前
一加12/Ace5/Ace3pro手机ColorOS16降级回锁BL熔断变黑砖怎么办
android·智能手机·电脑
Java面试题总结17 分钟前
Python 开发技巧 · 高级装饰器 —— 从基础到工业级实战
开发语言·python
纸小铭27 分钟前
[MAF预定义ChatClient中间件-01]LoggingChatClient——在调用LLM前后输出日志
python·中间件·flask
一路向北North31 分钟前
Spring Security OAuth2.0(19):JWT令牌
java·后端·spring
aiqianji34 分钟前
有哪些支持长文的AI生成短篇小说软件?
人工智能·python
玛卡巴卡ldf35 分钟前
【LeetCode 手撕算法】(细节知识点总结)
java·数据结构·算法·leetcode·力扣
狗都不学爬虫_44 分钟前
AI逆向 - 某定制瑞树6纯算(ck-header-params后缀)
爬虫·python·网络爬虫
三十岁老牛再出发1 小时前
07.08.&07.09.每日总结
c语言·python
Digitally1 小时前
使用 USB 数据线将文件从安卓设备传输到电脑
android·电脑
齐 飞1 小时前
Python常用语法总结
python