如何替换 Java 中 ArrayList 元素的现有值

新手上路,请多包涵

我正在尝试使用以下代码更新 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);
}

I want to print New instead of Two but I got [Zero, One, New, Two, Three] as the result, and I still have Two .我想打印 [Zero, One, New, Three] 。我怎样才能做到这一点?

原文由 Kani 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 776
2 个回答

使用 set 方法将旧值替换为新值。

 list.set( 2, "New" );

原文由 Bill the Lizard 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果您不知道要替换的位置,请使用列表迭代器查找和替换元素 ListIterator.set(E e)

 ListIterator<String> iterator = list.listIterator();
while (iterator.hasNext()) {
     String next = iterator.next();
     if (next.equals("Two")) {
         //Replace element
         iterator.set("New");
     }
 }

原文由 Sivabalan 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题