如何在 Java 中替换 ArrayList 元素的现有值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23981008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to replace existing value of ArrayList element in Java
提问by Kani
I am still quite new to Java programming and I am trying to update an existing value of an ArrayList
by using this code:
我对 Java 编程还是很陌生,我正在尝试ArrayList
使用以下代码更新 an 的现有值:
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
. I want to print [Zero, One, New, Three]
. How can I do this?
Thank You.
我想打印New
而不是打印,Two
但[Zero, One, New, Two, Three]
结果我得到了,而且我仍然有Two
. 我想打印[Zero, One, New, Three]
。我怎样才能做到这一点?谢谢你。
采纳答案by Bill the Lizard
回答by wonce
回答by Thwin Htoo Aung
You must use
你必须使用
list.remove(indexYouWantToReplace);
first.
第一的。
Your elements will become like this. [zero, one, three]
你的元素会变成这样。 [zero, one, three]
then add this
然后添加这个
list.add(indexYouWantedToReplace, newElement)
Your elements will become like this. [zero, one, new, three]
你的元素会变成这样。 [zero, one, new, three]
回答by Sivabalan
If you are unaware of the position to replace, use list iterator to find and replace element ListIterator.set(E e)
如果您不知道要替换的位置,请使用列表迭代器查找和替换元素 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");
}
}