如何在 Java 中替换 ArrayList 元素的现有值 [英] How to replace existing value of ArrayList element in Java

查看:32
本文介绍了如何在 Java 中替换 ArrayList 元素的现有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Java 编程还是很陌生,我正在尝试使用以下代码更新 ArrayList 的现有值:

I am still quite new to Java programming and I am trying to update an existing value of an ArrayList by using this code:

public static void main(String[] args) {

    List<String> list = new ArrayList<String>();

    list.add( "Zero" );
    list.add( "One" );
    list.add( "Two" );
    list.add( "Three" );

    list.add( 2, "New" ); // add at 2nd index

    System.out.println(list);
}

我想打印 New 而不是 Two 但我得到了 [Zero, One, New, Two, Three] 作为结果,而且我还有两个.我想打印[零,一,新,三].我怎样才能做到这一点?谢谢.

I want to print New instead of Two but I got [Zero, One, New, Two, Three] as the result, and I still have Two. I want to print [Zero, One, New, Three]. How can I do this? Thank You.

推荐答案

使用 set 用新值替换旧值的方法.

Use the set method to replace the old value with a new one.

list.set( 2, "New" );

这篇关于如何在 Java 中替换 ArrayList 元素的现有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆