开发者

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

This question already has answers here: Java ArrayList replace at specific index (6 answers) Closed 4 years ago.

I have one ArrayList of 10 Strings. How do I update the index 5开发者_开发百科 with another String value?


Let arrList be the ArrayList and newValue the new String, then just do:

arrList.set(5, newValue);

This can be found in the java api reference here.


list.set(5,"newString");  
  • Reference


 arrList.set(5,newValue);

and if u want to update it then add this line also

 youradapater.NotifyDataSetChanged();


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

    }
}}


arrayList.set(location,newValue); location= where u wnna insert, newValue= new element you are inserting.

notify is optional, depends on conditions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜