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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 16:24:33  来源:igfitidea点击:

How do I update the element at a certain position in an ArrayList?

javaarraylist

提问by Saravanan

I have one ArrayListof 10 Strings. How do I update the index 5with another Stringvalue?

我有ArrayList10String秒之一。如何5使用另一个String值更新索引?

采纳答案by HaskellElephant

Let arrListbe the ArrayListand newValuethe new String, then just do:

让我们arrList成为ArrayListnewValue新的String,然后就做:

arrList.set(5, newValue);

This can be found in the java api reference here.

这可以在此处的 java api 参考中找到

回答by Jigar Joshi

list.set(5,"newString");  

回答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);

    }
}}