我对 Java 编程还是很陌生,我正在尝试使用以下代码更新 ArrayList
的现有值:
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]
作为结果,我还有 Two
。我想打印 [零,一,新,三]
。我怎样才能做到这一点?
谢谢。
最佳答案
使用 set
用新值替换旧值的方法。
list.set( 2, "New" );
关于java - 如何在 Java 中替换 ArrayList 元素的现有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23981008/