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

JavaArraylist

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

list.set(5,"newString");  

Solution 3 - Java

 arrList.set(5,newValue);

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

 youradapater.NotifyDataSetChanged();

Solution 4 - Java

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

Solution 5 - Java

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

notify is optional, depends on conditions.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSaravananView Question on Stackoverflow
Solution 1 - JavaHaskellElephantView Answer on Stackoverflow
Solution 2 - JavajmjView Answer on Stackoverflow
Solution 3 - JavaRamzView Answer on Stackoverflow
Solution 4 - JavaIndianProgrammer1234View Answer on Stackoverflow
Solution 5 - JavaAndyView Answer on Stackoverflow