173

I have one ArrayList of 10 Strings. How do I update the index 5 with another String value?

0xCursor
  • 2,242
  • 4
  • 15
  • 33
Saravanan
  • 11,372
  • 43
  • 143
  • 213
  • 8
    Very common question for people new to Java's `ArrayList<>` library. The existence of the `set(pos, val)` method is not intuitive and doesn't fit with other Java paradigms. – SMBiggs Aug 02 '16 at 23:00
  • when you use the data class in kotlin, as follows : val modelData = ModelData() listData[index] = modelData – arjava Apr 22 '19 at 02:32

5 Answers5

347

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.

MaxChinni
  • 1,206
  • 14
  • 21
HaskellElephant
  • 9,819
  • 4
  • 38
  • 67
41
list.set(5,"newString");  
jmj
  • 237,923
  • 42
  • 401
  • 438
15
 arrList.set(5,newValue);

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

 youradapater.NotifyDataSetChanged();
Ramz
  • 658
  • 1
  • 7
  • 19
5
 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);

    }
}}
2

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

notify is optional, depends on conditions.

Andy
  • 189
  • 1
  • 2