Java 如何更新 ArrayList 中某个位置的元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4352885/
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 do I update the element at a certain position in an ArrayList?
提问by Saravanan
I have one ArrayList
of 10 String
s. How do I update the index 5
with another String
value?
我有ArrayList
10String
秒之一。如何5
使用另一个String
值更新索引?
采纳答案by HaskellElephant
回答by Ramz
arrList.set(5,newValue);
and if u want to update it then add this line also
如果你想更新它,那么也添加这一行
youradapater.NotifyDataSetChanged();
回答by Andy
arrayList.set(location,newValue); location= where u wnna insert, newValue= new element you are inserting.
arrayList.set(location,newValue); location=您要插入的位置,newValue=您要插入的新元素。
notify is optional, depends on conditions.
notify 是可选的,取决于条件。
回答by IndianProgrammer1234
import java.util.ArrayList;
import java.util.Iterator;
public class javaClass {
public static void main(String args[]) {
ArrayList<String> alstr = new ArrayList<>();
alstr.add("irfan");
alstr.add("yogesh");
alstr.add("kapil");
alstr.add("rajoria");
for(String str : alstr) {
System.out.println(str);
}
// update value here
alstr.set(3, "Ramveer");
System.out.println("with Iterator");
Iterator<String> itr = alstr.iterator();
while (itr.hasNext()) {
Object obj = itr.next();
System.out.println(obj);
}
}}