Change element in ArrayList Java
Update or Set Element of Java ArrayListTo 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. Show ArrayList.set() Reference to syntax and examples of set() method. Following is quick code snippet to use ArrayList.set() method. Example 1 Set Element of ArrayListIn 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) { ArrayListOutput Example 2 Set/Update Object of ArrayListIn the following example, we will create an ArrayList of Car objects, and update Car object of the list at index 2. Java Program import java.util.ArrayList; public class ArrayListExample { public static void main(String[] args) { ArrayListOutput cars.set(2, new Car("Tesla", 21400)); sets the element at index 2 with the new Car object passed as second argument. ConclusionIn this Java Tutorial, we learned how to set or update element of ArrayList in Java. |