Update or Set Element of Java ArrayList
To update or set an element or object at a given index of Java ArrayList, use ArrayList.set[] method. ArrayList.set[index, element] method updates the element of ArrayList at specified index with given element.
ArrayList.set[] Reference to syntax and examples of set[] method.
Following is quick code snippet to use ArrayList.set[] method.
myList.set[index, element];Example 1 Set Element of ArrayList
In the following example, we will update the element of an ArrayList at index 1.
Java Program
import java.util.ArrayList; public class ArrayListExample { public static void main[String[] args] { ArrayList names = new ArrayList[]; names.add["Google"]; names.add["Apple"]; names.add["Samsung"]; //update element of arraylist names.set[1, "Asus"]; for[String name: names] { System.out.println[name]; } } }Output
Google Asus SamsungExample 2 Set/Update Object of ArrayList
In the following example, we will create an ArrayList of Car objects, and update Car object of the list at index 2.
Java Program
Output
BMW travelled 52400 miles. Toyota travelled 66000 miles. Tesla travelled 21400 miles.cars.set[2, new Car["Tesla", 21400]]; sets the element at index 2 with the new Car object passed as second argument.
Conclusion
In this Java Tutorial, we learned how to set or update element of ArrayList in Java.