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<String> names = new ArrayList<String>();
		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
Samsung
ADVERTISEMENT

Example 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

import java.util.ArrayList;

public class ArrayListExample {
	public static void main(String[] args) {
		ArrayList<Car> cars = new ArrayList<Car>();
		cars.add(new Car("BMW", 52400));
		cars.add(new Car("Toyota", 66000));
		cars.add(new Car("Audi", 44000));
		
		//update object at index 2
		cars.set(2, new Car("Tesla", 21400));
		
		for(Car car: cars) {
			car.printDetails();
		}
	}
}

class Car {
	public String name;
	public int miles;
	
	public Car(String name, int miles) {
		this.name = name;
		this.miles = miles;
	}
	
	public void printDetails() {
		System.out.println(name + " travelled " + miles + " miles.");
	}
}

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.