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 小时前
【Android】CoordinatorLayout详解;实现一个交互动画的效果(上滑隐藏,下滑出现);附例子
android·kotlin·app
皮皮林5519 小时前
IDEA 源码阅读利器,你居然还不会?
java·intellij idea
databook12 小时前
Manim实现闪光轨迹特效
后端·python·动效
用户20187928316713 小时前
Android黑夜白天模式切换原理分析
android
芦半山13 小时前
「幽灵调用」背后的真相:一个隐藏多年的Android原生Bug
android
Juchecar14 小时前
解惑:NumPy 中 ndarray.ndim 到底是什么?
python
卡尔特斯14 小时前
Android Kotlin 项目代理配置【详细步骤(可选)】
android·java·kotlin
ace望世界14 小时前
安卓的ViewModel
android
白鲸开源14 小时前
Ubuntu 22 下 DolphinScheduler 3.x 伪集群部署实录
java·ubuntu·开源
ace望世界14 小时前
kotlin的委托
android