How to update elements of a list in Java?

To update the objects in the List, you can achieve it by following these steps:

  1. Firstly, obtain the index position of the object to be updated in the List.
  2. Then use the set() method of List to replace the original object with a new object.
  3. Finally, the updated List will be printed out or further actions can be taken.

Here is an example code:

import java.util.ArrayList;
import java.util.List;

public class UpdateListElements {
    public static void main(String[] args) {
        // 创建一个List并添加对象元素
        List<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Orange");

        // 打印原始List
        System.out.println("Original List: " + list);

        // 更新List中的对象元素
        String newElement = "Mango";
        int index = 1; // 要更新的对象在List中的索引位置
        list.set(index, newElement);

        // 打印更新后的List
        System.out.println("Updated List: " + list);
    }
}

In the example above, we created a List containing String objects and updated the object at index position 1 to “Mango”. Finally, we printed the updated List.

bannerAds