168

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

0xCursor
  • 2,230
  • 4
  • 14
  • 32
Saravanan
  • 11,084
  • 42
  • 137
  • 209
  • 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

338

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,116
  • 12
  • 20
HaskellElephant
  • 9,669
  • 4
  • 35
  • 67
40
list.set(5,"newString");  
jmj
  • 232,312
  • 42
  • 391
  • 431
15
 arrList.set(5,newValue);

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

 youradapater.NotifyDataSetChanged();
Ramz
  • 648
  • 7
  • 19
4
 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);

    }
}}
1

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

notify is optional, depends on conditions.

Andy
  • 169
  • 1
  • 2