I have one ArrayList
of 10 String
s. How do I update the index 5
with another String
value?
Asked
Active
Viewed 3e+01k times
173
-
8Very 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 Answers
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
-
I think you mean index 5 as the ArrayList has only 10 elements and this would blow up. ;) – Peter Lawrey Dec 04 '10 at 09:53
-
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);
}
}}

IndianProgrammer1234
- 480
- 6
- 14
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